<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>C++效率掌握之STL库：map &amp;&amp; set底层剖析及迭代器万字详解 | 澪贰</title><meta name="author" content="澪贰"><meta name="copyright" content="澪贰"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="ffffff"><meta name="description" content="map、set的封装可以说是很天才的底层结构了，本篇将对其结构进行详细的解析，虽然会很复杂且难以理解，但是学完成就感满满，而且对底层理解和面试很有帮助">
<meta property="og:type" content="article">
<meta property="og:title" content="C++效率掌握之STL库：map &amp;&amp; set底层剖析及迭代器万字详解">
<meta property="og:url" content="http://example.com/2025/05/14/CPP%E8%BF%9B%E9%98%B6/map%20&&%20set%E5%BA%95%E5%B1%82%E5%89%96%E6%9E%90%E5%8F%8A%E8%BF%AD%E4%BB%A3%E5%99%A8%E4%B8%87%E5%AD%97%E8%AF%A6%E8%A7%A3/index.html">
<meta property="og:site_name" content="澪贰">
<meta property="og:description" content="map、set的封装可以说是很天才的底层结构了，本篇将对其结构进行详细的解析，虽然会很复杂且难以理解，但是学完成就感满满，而且对底层理解和面试很有帮助">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250511012240.jpg">
<meta property="article:published_time" content="2025-05-14T13:39:02.000Z">
<meta property="article:modified_time" content="2025-05-14T13:39:02.000Z">
<meta property="article:author" content="澪贰">
<meta property="article:tag" content="C++">
<meta property="article:tag" content="stl">
<meta property="article:tag" content="map">
<meta property="article:tag" content="set">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250511012240.jpg"><script type="application/ld+json">{
  "@context": "https://schema.org",
  "@type": "BlogPosting",
  "headline": "C++效率掌握之STL库：map && set底层剖析及迭代器万字详解",
  "url": "http://example.com/2025/05/14/CPP%E8%BF%9B%E9%98%B6/map%20&&%20set%E5%BA%95%E5%B1%82%E5%89%96%E6%9E%90%E5%8F%8A%E8%BF%AD%E4%BB%A3%E5%99%A8%E4%B8%87%E5%AD%97%E8%AF%A6%E8%A7%A3/",
  "image": "https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250511012240.jpg",
  "datePublished": "2025-05-14T13:39:02.000Z",
  "dateModified": "2025-05-14T13:39:02.000Z",
  "author": [
    {
      "@type": "Person",
      "name": "澪贰",
      "url": "http://example.com/"
    }
  ]
}</script><link rel="shortcut icon" href="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/cat_icon.ico"><link rel="canonical" href="http://example.com/2025/05/14/CPP%E8%BF%9B%E9%98%B6/map%20&amp;&amp;%20set%E5%BA%95%E5%B1%82%E5%89%96%E6%9E%90%E5%8F%8A%E8%BF%AD%E4%BB%A3%E5%99%A8%E4%B8%87%E5%AD%97%E8%AF%A6%E8%A7%A3/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><script>
    (() => {
      
    const saveToLocal = {
      set: (key, value, ttl) => {
        if (!ttl) return
        const expiry = Date.now() + ttl * 86400000
        localStorage.setItem(key, JSON.stringify({ value, expiry }))
      },
      get: key => {
        const itemStr = localStorage.getItem(key)
        if (!itemStr) return undefined
        const { value, expiry } = JSON.parse(itemStr)
        if (Date.now() > expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return value
      }
    }

    window.btf = {
      saveToLocal,
      getScript: (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        Object.entries(attr).forEach(([key, val]) => script.setAttribute(key, val))
        script.onload = script.onreadystatechange = () => {
          if (!script.readyState || /loaded|complete/.test(script.readyState)) resolve()
        }
        script.onerror = reject
        document.head.appendChild(script)
      }),
      getCSS: (url, id) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onload = link.onreadystatechange = () => {
          if (!link.readyState || /loaded|complete/.test(link.readyState)) resolve()
        }
        link.onerror = reject
        document.head.appendChild(link)
      }),
      addGlobalFn: (key, fn, name = false, parent = window) => {
        if (!true && key.startsWith('pjax')) return
        const globalFn = parent.globalFn || {}
        globalFn[key] = globalFn[key] || {}
        globalFn[key][name || Object.keys(globalFn[key]).length] = fn
        parent.globalFn = globalFn
      }
    }
  
      
      const activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      const activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', 'ffffff')
        }
      }

      btf.activateDarkMode = activateDarkMode
      btf.activateLightMode = activateLightMode

      const theme = saveToLocal.get('theme')
    
          const hour = new Date().getHours()
          const isNight = hour <= 6 || hour >= 18
          if (theme === undefined) isNight ? activateDarkMode() : activateLightMode()
          else theme === 'light' ? activateLightMode() : activateDarkMode()
        
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        document.documentElement.classList.toggle('hide-aside', asideStatus === 'hide')
      }
    
      
    const detectApple = () => {
      if (/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)) {
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
  
    })()
  </script><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":true,"top_n_per_article":1,"unescape":false,"languages":{"hits_empty":"未找到符合您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":230,"highlightFullpage":false,"highlightMacStyle":false},
  copy: {
    success: '复制成功',
    error: '复制失败',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '天',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":150,"languages":{"author":"作者: 澪贰","link":"链接: ","source":"来源: 澪贰","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'medium_zoom',
  Snackbar: {"chs_to_cht":"已切换为繁体中文","cht_to_chs":"已切换为简体中文","day_to_night":"已切换为深色模式","night_to_day":"已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"top-right"},
  infinitegrid: {
    js: 'https://cdn.jsdelivr.net/npm/@egjs/infinitegrid/dist/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyloadPlugin: true,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'C++效率掌握之STL库：map && set底层剖析及迭代器万字详解',
  isHighlightShrink: false,
  isToc: true,
  pageType: 'post'
}</script><link rel="stylesheet" href="/css/custom.css" media="defer" onload="this.media='all'"><script src="https://npm.elemecdn.com/echarts@4.9.0/dist/echarts.min.js"></script><!-- hexo injector head_end start --><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Zfour/Butterfly-double-row-display@1.00/cardlistpost.min.css"/>
<style>#recent-posts > .recent-post-item >.recent-post-info > .article-meta-wrap > .tags:before {content:"\A";
  white-space: pre;}#recent-posts > .recent-post-item >.recent-post-info > .article-meta-wrap > .tags > .article-meta__separator{display:none}</style>
<link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-categories-card@1.0.0/lib/categorybar.css"><link rel="stylesheet" href="https://unpkg.zhimg.com/hexo-butterfly-footer-beautify@1.0.0/lib/runtime.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiper.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiperstyle.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-filter-gitcalendar/lib/gitcalendar.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-wowjs/lib/animate.min.css" media="print" onload="this.media='screen'"><!-- hexo injector head_end end --><meta name="generator" content="Hexo 7.3.0"></head><body><div id="web_bg" style="background-image: url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/water02.jpg);"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img text-center"><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/zero_two.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data text-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">96</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">74</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">9</div></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home-lg"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><span class="site-page group hide"><i class="fa-fw fas fa-list"></i><span> 列表</span><i class="fas fa-chevron-down"></i></span><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/comments/"><i class="fa-fw fas fa-envelope-open"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250511012240.jpg);"><nav id="nav"><span id="blog-info"><a class="nav-site-title" href="/"><span class="site-name">澪贰</span></a><a class="nav-page-title" href="/"><span class="site-name">C++效率掌握之STL库：map &amp;&amp; set底层剖析及迭代器万字详解</span></a></span><div id="menus"><div id="search-button"><span class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></span></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home-lg"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><span class="site-page group hide"><i class="fa-fw fas fa-list"></i><span> 列表</span><i class="fas fa-chevron-down"></i></span><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/comments/"><i class="fa-fw fas fa-envelope-open"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><span class="site-page"><i class="fas fa-bars fa-fw"></i></span></div></div></nav><div id="post-info"><h1 class="post-title">C++效率掌握之STL库：map &amp;&amp; set底层剖析及迭代器万字详解</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2025-05-14T13:39:02.000Z" title="发表于 2025-05-14 21:39:02">2025-05-14</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2025-05-14T13:39:02.000Z" title="更新于 2025-05-14 21:39:02">2025-05-14</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/C-%E8%BF%9B%E9%98%B6/">C++进阶</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">总字数:</span><span class="word-count">4323</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>19分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title=""><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">浏览量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="container post-content" id="article-container"><div id="post-outdate-notice" data="{&quot;limitDay&quot;:365,&quot;messagePrev&quot;:&quot;It has been&quot;,&quot;messageNext&quot;:&quot;days since the last update, the content of the article may be outdated.&quot;,&quot;postUpdate&quot;:&quot;2025-05-14 21:39:02&quot;}" hidden></div><p><code>map</code>、<code>set</code> 的封装可以说是很天才的底层结构了，本篇将对其结构进行详细的解析，虽然会很复杂且难以理解，但是学完成就感满满，而且对底层理解和面试很有帮助</p>
<h1 id="map、set的基本结构"><a href="#map、set的基本结构" class="headerlink" title="map、set的基本结构"></a>map、set的基本结构</h1><p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/e68d1a6b6e0844da91d43af3063303e1.png" alt="在这里插入图片描述"></p>
<p>通过查看官方文档，截取部分关键代码，我们可以发现 <code>set</code> 虽然事 <code>k-k</code> 类型，<code>map</code> 是 <code>k-v</code> 类型，但是实际上这两个类共用一个红黑树，准确来说是共用同一个模板类型，<code>set</code> 是 <code>&lt;K，K&gt;</code>，<code>map</code> 是 <code>&lt;K，pair&lt;K，V&gt;&gt;</code>，下面会进行详细解析</p>
<ul>
<li><code>size_type node_count</code>：用于记录红黑树节点数量，跟踪树的大小</li>
<li><code>link_type header</code>：是指向红黑树头节点的指针</li>
<li><code>Value value_field</code>：存储节点的值</li>
</ul>
<p>那么下面我们将自己实现简单的 <code>set</code> 和 <code>map</code> 类：</p>
<h1 id="map、set模拟实现"><a href="#map、set模拟实现" class="headerlink" title="map、set模拟实现"></a>map、set模拟实现</h1><h2 id="初步定义"><a href="#初步定义" class="headerlink" title="初步定义"></a>初步定义</h2><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span>&lt;<span class="keyword">class</span> <span class="title class_">K</span>&gt;</span><br><span class="line"><span class="keyword">class</span> <span class="title class_">set</span></span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">	RBTree&lt;K, K&gt; <span class="type">_t</span>;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">template</span>&lt;<span class="keyword">class</span> <span class="title class_">K</span>, <span class="keyword">class</span> <span class="title class_">V</span>&gt;</span><br><span class="line"><span class="keyword">class</span> <span class="title class_">map</span></span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">	RBTree&lt;K, pair&lt;<span class="type">const</span> K, V&gt;, MapKeyOfT&gt; <span class="type">_t</span>;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>平常我们认为键值对指的就是 <code>K</code> 和 <code>V</code>，但是在库里不是这样的，库里的 <code>K</code> 表示键值对的类型，<code>V</code> 表示插入红黑树的键值对，只不过对于 <code>set</code> 来说，<code>K</code> 和 <code>V</code> 是一样的</p>
<p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/78c5df437a1b43729930fe5554222438.png" alt="在这里插入图片描述"></p>
<p>在红黑树中，定义的模板参数 <code>T</code>，而不是原先的 <code>pair</code>，这里的 <code>T</code> 表示插入的数据 <code>_data</code> 的类型，这种定义方法能够共同使用同一参数模板，避免额外的代码编写</p>
<h2 id="仿函数实现"><a href="#仿函数实现" class="headerlink" title="仿函数实现"></a>仿函数实现</h2><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span>&lt;<span class="keyword">class</span> <span class="title class_">K</span>&gt;</span><br><span class="line"><span class="keyword">class</span> <span class="title class_">set</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="keyword">struct</span> <span class="title class_">SetKeyOfT</span></span><br><span class="line">	&#123;</span><br><span class="line">		<span class="function"><span class="type">const</span> K&amp; <span class="title">operator</span><span class="params">()</span><span class="params">(<span class="type">const</span> K&amp; key)</span></span></span><br><span class="line"><span class="function">		</span>&#123;</span><br><span class="line">			<span class="keyword">return</span> key;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;;</span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">	RBTree&lt;K, K, SetKeyOfT&gt; <span class="type">_t</span>;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">template</span>&lt;<span class="keyword">class</span> <span class="title class_">K</span>, <span class="keyword">class</span> <span class="title class_">V</span>&gt;</span><br><span class="line"><span class="keyword">class</span> <span class="title class_">map</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="keyword">struct</span> <span class="title class_">MapKeyOfT</span></span><br><span class="line">	&#123;</span><br><span class="line">		<span class="function"><span class="type">const</span> K&amp; <span class="title">operator</span><span class="params">()</span><span class="params">(<span class="type">const</span> pair&lt;K, V&gt;&amp; kv)</span></span></span><br><span class="line"><span class="function">		</span>&#123;</span><br><span class="line">			<span class="keyword">return</span> kv.first;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;;</span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">	RBTree&lt;K, pair&lt;<span class="type">const</span> K, V&gt;, MapKeyOfT&gt; <span class="type">_t</span>;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>我们知道 <code>set</code> 和 <code>map</code> 是通过比较 <code>key</code>，在红黑树中来插入的，但是由于上述的定义，如果每次对于 <code>map</code> 都频繁取出 <code>first</code> 就太麻烦了，因此就定义了仿函数</p>
<p>🚩<strong>为什么使用仿函数而不是普通函数呢？</strong></p>
<blockquote>
<p>红黑树中只要涉及到数据 <code>_data</code> 的地方，就需要使用到仿函数提取 <code>key</code>，使用普通函数消耗太大，而仿函数带有 <code>inline</code> 的性质，降低消耗。同时官方文档中还对比较进行了实现，即 <code>Compare</code>，模板要求参数必须是一个类型，而普通函数无法作为类型传递</p>
</blockquote>
<p>🚩<strong>为什么要自己定义仿函数，pair自带的仿函数不行吗？</strong></p>
<p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/a91c9d67824a45aabf039c9eb00ec0de.png" alt="在这里插入图片描述"><br>虽然 <code>pair</code> 确实有自己的仿函数比较，但是他是比较完 <code>first</code> 后不行，会接着比较 <code>second</code>，这不符合我们的设计思路</p>
<hr>
<p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/4d593e6f7b2c47e99ece8998edee1aaf.png" alt="在这里插入图片描述"></p>
<p>截取了部分 <code>insert</code> 中的代码，利用仿函数确实是能够简单的实现键值 <code>first</code> 的提取，我们再对整体的调用思路进行整理</p>
<p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/12e5584389b445a1afc3d3c4a07ce5a5.png" alt="在这里插入图片描述"></p>
<p>其实仿函数主要是为了 <code>map</code> 而设计的，为的就是提取 <code>first</code>，<code>set</code> 为了保持设计模式的一致，因而也设计了相同的仿函数，这样就不用关心是否需要调用这一点了，保持一致性</p>
<p>这里我们不对 <code>Compare</code> 进行实现，有兴趣的可以自己去看底层代码</p>
<p>🔥<strong>值得注意的是：</strong> 仿函数内不实现比较功能是因为，比较功能是一个外层调用功能，如果放在内部就不能操作者自行去调用了，况且 <code>Compare</code> 也是以仿函数的形式实现的，两个仿函数嵌套过于复杂，不好使用</p>
<h2 id="Find功能实现"><a href="#Find功能实现" class="headerlink" title="Find功能实现"></a>Find功能实现</h2><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">Node* <span class="title">Find</span><span class="params">(<span class="type">const</span> K&amp; key)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	Node* cur = _root;</span><br><span class="line">	KeyOfT kot;</span><br><span class="line">	<span class="keyword">while</span> (cur)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="keyword">if</span> (<span class="built_in">kot</span>(cur-&gt;_data) &lt; key)</span><br><span class="line">		&#123;</span><br><span class="line">			cur = cur-&gt;_right;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> <span class="keyword">if</span> (<span class="built_in">kot</span>(cur-&gt;_data) &gt; key)</span><br><span class="line">		&#123;</span><br><span class="line">			cur = cur-&gt;_left;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span></span><br><span class="line">		&#123;</span><br><span class="line">			<span class="keyword">return</span> cur;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="literal">nullptr</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="迭代器初步功能实现"><a href="#迭代器初步功能实现" class="headerlink" title="迭代器初步功能实现"></a>迭代器初步功能实现</h2><p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/0f8fc160755b406a8782ad7bc94b69da.png" alt="在这里插入图片描述"></p>
<p>类似的迭代器分析我们在 <code>list</code> 部分有做过解析，确实大体上是相像的，但是结构并不一样，这里的树形结构需要以中序遍历：<code>左-根-右</code>的方式遍历</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span>&lt;<span class="keyword">class</span> <span class="title class_">T</span>&gt;</span><br><span class="line"><span class="keyword">struct</span> <span class="title class_">__TreeIterator</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="keyword">typedef</span> RBTreeNode&lt;T&gt; Node;</span><br><span class="line">	<span class="keyword">typedef</span> __TreeIterator&lt;T&gt; Self;</span><br><span class="line">	Node* _node;</span><br><span class="line"></span><br><span class="line">	__TreeIterator(Node* node)</span><br><span class="line">		:_node(node)</span><br><span class="line">	&#123;&#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>库里的迭代器模式并不能满足我们的设计需要，所以这里自己构建一个 <code>__TreeIterator</code> 类</p>
<h3 id="运算符重载"><a href="#运算符重载" class="headerlink" title="++运算符重载"></a>++运算符重载</h3><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line">Self&amp; <span class="keyword">operator</span>++()</span><br><span class="line">&#123;</span><br><span class="line">	<span class="keyword">if</span> (_node-&gt;_right)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="comment">// 右树的最左节点(最小节点)</span></span><br><span class="line">		Node* subLeft = _node-&gt;_right;</span><br><span class="line">		<span class="keyword">while</span> (subLeft-&gt;_left)</span><br><span class="line">		&#123;</span><br><span class="line">			subLeft = subLeft-&gt;_left;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		_node = subLeft;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span></span><br><span class="line">	&#123;</span><br><span class="line">		Node* cur = _node;</span><br><span class="line">		Node* parent = cur-&gt;_parent;</span><br><span class="line">		<span class="comment">// 找孩子是父亲左的那个祖先节点，就是下一个要访问的节点</span></span><br><span class="line">		<span class="keyword">while</span> (parent)</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="keyword">if</span> (cur == parent-&gt;_left)</span><br><span class="line">			&#123;</span><br><span class="line">				<span class="keyword">break</span>;</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">else</span></span><br><span class="line">			&#123;</span><br><span class="line">				cur = cur-&gt;_parent;</span><br><span class="line">				parent = parent-&gt;_parent;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		_node = parent;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> *<span class="keyword">this</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>中序遍历的方式是 <code>左-根-右</code>，因此可以总结为两种情况来遍历：</p>
<ul>
<li><strong>当前节点有右子树</strong></li>
</ul>
<p><strong>处理方式：</strong> 找到右子树的最左节点（即右子树中的最小值）</p>
<p><strong>原因：</strong> 在中序遍历中，当前节点的下一个节点是其右子树的最左节点</p>
<ul>
<li><strong>当前节点没有右子树</strong></li>
</ul>
<p><strong>处理方式：</strong> 向上回溯，直到找到某个祖先节点，使得当前节点位于该祖先的左子树中</p>
<p><strong>原因：</strong> 在中序遍历中，若无右子树，则下一个节点是第一个满足 “当前节点是其左子节点” 的祖先</p>
<p>🔥<strong>值得注意的是：</strong> 当前节点没有右子树的情况，是 <code>左-根-右</code> 的最后一步，无论是在根的左边还是右边，最终都会回到根节点，所以直接 <code>_node = parent</code> 即可</p>
<h3 id="–运算符重载"><a href="#–运算符重载" class="headerlink" title="–运算符重载"></a>–运算符重载</h3><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">Self&amp; <span class="keyword">operator</span>--()</span><br><span class="line">&#123;</span><br><span class="line">	<span class="keyword">if</span> (_node-&gt;_left)</span><br><span class="line">	&#123;</span><br><span class="line">		Node* subRight = _node-&gt;_left;</span><br><span class="line">		<span class="keyword">while</span> (subRight-&gt;_right)</span><br><span class="line">		&#123;</span><br><span class="line">			subRight = subRight-&gt;_right;</span><br><span class="line">		&#125;</span><br><span class="line">		_node = subRight;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span></span><br><span class="line">	&#123;</span><br><span class="line">		<span class="comment">// 孩子是父亲的右的那个节点</span></span><br><span class="line">		Node* cur = _node;</span><br><span class="line">		Node* parent = cur-&gt;_parent;</span><br><span class="line">		<span class="keyword">while</span> (parent &amp;&amp; cur == parent-&gt;_left)</span><br><span class="line">		&#123;</span><br><span class="line">			cur = cur-&gt;_parent;</span><br><span class="line">			parent = parent-&gt;_parent;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		_node = parent;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> *<span class="keyword">this</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>operator--</code>  的思路和 <code>operator++</code> 是一样的，反过来遍历就行了</p>
<h3 id="运算符重载-1"><a href="#运算符重载-1" class="headerlink" title="*运算符重载"></a>*运算符重载</h3><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">T&amp; <span class="keyword">operator</span>*()</span><br><span class="line">&#123;</span><br><span class="line">	<span class="keyword">return</span> _node-&gt;_data;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="运算符重载-2"><a href="#运算符重载-2" class="headerlink" title="-&gt;运算符重载"></a>-&gt;运算符重载</h3><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">T* <span class="keyword">operator</span>-&gt;()</span><br><span class="line">&#123;</span><br><span class="line">	<span class="keyword">return</span> &amp;_node-&gt;_data;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里再提醒一下重载 <code>-&gt;</code> 是因为用 <code>*</code> 的代码不够简洁，具体分析参考 <code>list</code> 部分的解析</p>
<blockquote>
<p>传送门：<a target="_blank" rel="noopener" href="https://blog.csdn.net/Zero_VPN/article/details/146324257?spm=1001.2014.3001.5501">C++效率掌握之STL库：list底层剖析及迭代器万字详解</a></p>
</blockquote>
<h3 id="运算符重载-3"><a href="#运算符重载-3" class="headerlink" title="!&#x3D;运算符重载"></a>!&#x3D;运算符重载</h3><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">bool</span> <span class="keyword">operator</span>!=(<span class="type">const</span> Self&amp; s) <span class="type">const</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="keyword">return</span> _node != s._node;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>_node</code>：当前迭代器指向的节点<br><code>s._node</code>：另一个迭代器（作为参数传入）指向的节点</p>
<h3 id="begin"><a href="#begin" class="headerlink" title="begin()"></a>begin()</h3><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//RBTree.h</span></span><br><span class="line"><span class="function">iterator <span class="title">begin</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	Node* leftMin = _root;</span><br><span class="line">	<span class="keyword">while</span> (leftMin &amp;&amp; leftMin-&gt;_left)</span><br><span class="line">	&#123;</span><br><span class="line">		leftMin = leftMin-&gt;_left;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">return</span> <span class="built_in">iterator</span>(leftMin);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//Set.h Map.h</span></span><br><span class="line"><span class="function">iterator <span class="title">begin</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="type">_t</span>.<span class="built_in">begin</span>();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="end"><a href="#end" class="headerlink" title="end()"></a>end()</h3><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//RBTree.h</span></span><br><span class="line"><span class="function">iterator <span class="title">end</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="built_in">iterator</span>(<span class="literal">nullptr</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//Set.h Map.h</span></span><br><span class="line"><span class="function">iterator <span class="title">end</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="type">_t</span>.<span class="built_in">end</span>();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<p>现在已经可以基本实现遍历的功能了</p>
<h2 id="迭代器进阶功能实现"><a href="#迭代器进阶功能实现" class="headerlink" title="迭代器进阶功能实现"></a>迭代器进阶功能实现</h2><h3 id="set：const迭代器及insert的实现"><a href="#set：const迭代器及insert的实现" class="headerlink" title="set：const迭代器及insert的实现"></a>set：const迭代器及insert的实现</h3><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">typedef</span> <span class="keyword">typename</span> RBTree&lt;K, K, SetKeyOfT&gt;::const_iterator iterator;</span><br><span class="line"><span class="keyword">typedef</span> <span class="keyword">typename</span> RBTree&lt;K, K, SetKeyOfT&gt;::const_iterator const_iterator;</span><br><span class="line"></span><br><span class="line"><span class="function">const_iterator <span class="title">begin</span><span class="params">()</span> <span class="type">const</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="type">_t</span>.<span class="built_in">begin</span>();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function">const_iterator <span class="title">end</span><span class="params">()</span> <span class="type">const</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="type">_t</span>.<span class="built_in">end</span>();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>由于 <code>set</code> 规定 <code>key</code> 是不可以被修改的，因此 <code>iterator</code> 和 <code>const_iterator</code> 本质上其实都是<code>const_iterator</code></p>
<p>🔥<strong>值得注意的是：</strong> <code>begin()</code> 和 <code>end()</code> 的 <code>const</code> 迭代器函数被 <code>const</code> 修饰是为了满足常量容器对象或非常量容器对象都能调用</p>
<hr>
<p><code>insert</code> 的错误代码：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">pair&lt;iterator, <span class="type">bool</span>&gt; <span class="title">insert</span><span class="params">(<span class="type">const</span> K&amp; key)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="type">_t</span>.<span class="built_in">Insert</span>(key);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里是返回红黑树的插入，红黑树的插入详见下面的代码展示</p>
<p>从之前的学习我们知道 <code>insert</code> 返回的是 <code>pair&lt;iterator, bool&gt;</code>，那么是不是直接返回insert的结果就好了呢？看似确实是没问题，但是这里理了个巨大的坑，我们实际分析一波：</p>
<ul>
<li><code>_t.Insert(key)</code> 返回的是 <code>RBTree::iterator</code>，是一个普通迭代器</li>
<li><code>pair&lt;iterator, bool&gt; insert(const K&amp; key)</code> 返回的是 <code>set::iterator</code>，是一个 <code>const</code> 迭代器</li>
</ul>
<p><code>insert</code> 的正确代码：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// iterator RBTree::const_iterator</span></span><br><span class="line"><span class="function">pair&lt;iterator, <span class="type">bool</span>&gt; <span class="title">insert</span><span class="params">(<span class="type">const</span> K&amp; key)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="comment">// pair&lt;RBTree::iterator, bool&gt;</span></span><br><span class="line">	pair&lt;<span class="keyword">typename</span> RBTree&lt;K, K, SetKeyOfT&gt;::iterator, <span class="type">bool</span>&gt; ret = <span class="type">_t</span>.<span class="built_in">Insert</span>(key);</span><br><span class="line">	<span class="keyword">return</span> <span class="built_in">pair</span>&lt;iterator, <span class="type">bool</span>&gt;(ret.first, ret.second);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>正确的做法是先将 <code>insert</code> 返回的普通迭代器由变量 <code>ret</code> 存储，然后再用一个匿名对象进行构造，将 <code>ret</code> 的普通迭代器构造成 <code>const</code> 迭代器返回即可，下面将进行详细的构造原理解释：</p>
<p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/e75c8299ed0d4935bdce59c8470482ab.png" alt="在这里插入图片描述"></p>
<p>回看官方文档发现 <code>iterator</code> 和 <code>const_iterator</code> 都是被单独拿出来实例化的，并没有受到 <code>Ref</code> 和 <code>Ptr</code> 的影响，那么此时就分为两种情况：</p>
<ul>
<li><strong>普通迭代器的拷贝构造</strong></li>
</ul>
<p>当  <code>__rb_tree_iterator</code> 是普通迭代器时，<code>iterator</code> 就是自身类型，此时构造函数等价于：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">__rb_tree_iterator(<span class="type">const</span> __rb_tree_iterator&lt;Value, Value&amp;, Value*&gt;&amp; it)</span><br><span class="line">    : <span class="built_in">node</span>(it.node) </span><br><span class="line">    &#123;&#125;</span><br></pre></td></tr></table></figure>

<p>这是一个标准的拷贝构造函数，用于创建一个新的普通迭代器，指向相同的节点</p>
<ul>
<li><strong>const迭代器的构造</strong></li>
</ul>
<p>当 <code>__rb_tree_iterator</code> 是 <code>const</code> 迭代器时， <code>iterator</code> 指的是普通迭代器类型，此时构造函数等价于：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">__rb_tree_iterator(<span class="type">const</span> __rb_tree_iterator&lt;Value, Value&amp;, Value*&gt;&amp; it)</span><br><span class="line">    : <span class="built_in">node</span>(it.node) </span><br><span class="line">    &#123;&#125;</span><br></pre></td></tr></table></figure>

<p>这变成了一个构造函数，允许从普通迭代器创建 <code>const</code> 迭代器</p>
<p>所以可以理解为单独拿出来实例化是为了不让 <code>Ref</code> 和 <code>Ptr</code> 影响参数，而外面的类型就会受 <code>Ref</code> 和 <code>Ptr</code> 影响，这样就能保证外面的类型是 <code>const</code> 迭代器，里面的参数是普通迭代器，成功构造出一个支持普通迭代器构造 <code>const</code> 迭代器的构造函数</p>
<p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/43809235b03f493eb4440fcf8d1b2673.png" alt="在这里插入图片描述"></p>
<p>那再转到实际代码上，<code>ret.first</code> 的类型是 <code>typename RBTree&lt;K, K, SetKeyOfT&gt;::iterator</code> ，返回值 <code>pair</code> 的第一个元素类型是 <code>set</code> 类中定义的 <code>iterator</code>，实际上是 <code>typename RBTree&lt;K, K, SetKeyOfT&gt;::const_iterator</code></p>
<p><code>ret.first</code> 会调用自定义的迭代器类型的构造函数 <code>__TreeIterator(const Iterator&amp; it)</code> 进行单参数转换，变成 <code>const_iterator</code></p>
<h3 id="map：const迭代器及insert、-运算符重载的实现"><a href="#map：const迭代器及insert、-运算符重载的实现" class="headerlink" title="map：const迭代器及insert、[ ]运算符重载的实现"></a>map：const迭代器及insert、[ ]运算符重载的实现</h3><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">typedef</span> <span class="keyword">typename</span> RBTree&lt;K, pair&lt;<span class="type">const</span> K, V&gt;, MapKeyOfT&gt;::iterator iterator;</span><br><span class="line"><span class="keyword">typedef</span> <span class="keyword">typename</span> RBTree&lt;K, pair&lt;<span class="type">const</span> K, V&gt;, MapKeyOfT&gt;::const_iterator const_iterator;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function">iterator <span class="title">begin</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="type">_t</span>.<span class="built_in">begin</span>();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function">iterator <span class="title">end</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="type">_t</span>.<span class="built_in">end</span>();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function">const_iterator <span class="title">begin</span><span class="params">()</span> <span class="type">const</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="type">_t</span>.<span class="built_in">begin</span>();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function">const_iterator <span class="title">end</span><span class="params">()</span> <span class="type">const</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="type">_t</span>.<span class="built_in">end</span>();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>对于 <code>map</code> 来说，<code>key</code> 是不允许改变的，<code>value</code> 是可以改变的，但是如果像 <code>set</code> 那样写的话 <code>key</code> 和 <code>value</code> 都不能修改了，所以直接在 <code>pair</code> 的 <code>key</code> 加 <code>const</code> ，控制 <code>value</code> 即可</p>
<p>–<br><code>insert</code> 代码：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">pair&lt;iterator, <span class="type">bool</span>&gt; <span class="title">insert</span><span class="params">(<span class="type">const</span> pair&lt;K, V&gt;&amp; kv)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="type">_t</span>.<span class="built_in">Insert</span>(kv);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>map</code> 就没有像 <code>set</code> 那么麻烦了，红黑树和 &#96;map 的迭代器是一致的</p>
<hr>
<p><code>[ ]运算符重载</code> 代码：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">V&amp; <span class="keyword">operator</span>[](<span class="type">const</span> K&amp; key)</span><br><span class="line">&#123;</span><br><span class="line">	pair&lt;iterator, <span class="type">bool</span>&gt; ret = <span class="built_in">insert</span>(<span class="built_in">make_pair</span>(key, <span class="built_in">V</span>()));</span><br><span class="line">	<span class="keyword">return</span> ret.first-&gt;second;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>之前详细解释过，可以看之前的博客</p>
<blockquote>
<p>传送门：<a target="_blank" rel="noopener" href="https://blog.csdn.net/Zero_VPN/article/details/147564088?spm=1001.2014.3001.5501">C++漫溯键值的长河：map &amp;&amp; set</a></p>
</blockquote>
<h1 id="3-代码展示"><a href="#3-代码展示" class="headerlink" title="3.代码展示"></a>3.代码展示</h1><p>🚩<strong>MySet.h</strong></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">pragma</span> once</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&quot;RBTree.h&quot;</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">namespace</span> bit</span><br><span class="line">&#123;</span><br><span class="line">	<span class="keyword">template</span>&lt;<span class="keyword">class</span> <span class="title class_">K</span>&gt;</span><br><span class="line">	<span class="keyword">class</span> <span class="title class_">set</span></span><br><span class="line">	&#123;</span><br><span class="line">		<span class="keyword">struct</span> <span class="title class_">SetKeyOfT</span></span><br><span class="line">		&#123;</span><br><span class="line">			<span class="function"><span class="type">const</span> K&amp; <span class="title">operator</span><span class="params">()</span><span class="params">(<span class="type">const</span> K&amp; key)</span></span></span><br><span class="line"><span class="function">			</span>&#123;</span><br><span class="line">				<span class="keyword">return</span> key;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;;</span><br><span class="line">	<span class="keyword">public</span>:</span><br><span class="line">		<span class="keyword">typedef</span> <span class="keyword">typename</span> RBTree&lt;K, K, SetKeyOfT&gt;::const_iterator iterator;</span><br><span class="line">		<span class="keyword">typedef</span> <span class="keyword">typename</span> RBTree&lt;K, K, SetKeyOfT&gt;::const_iterator const_iterator;</span><br><span class="line"></span><br><span class="line">		<span class="function">const_iterator <span class="title">begin</span><span class="params">()</span> <span class="type">const</span></span></span><br><span class="line"><span class="function">		</span>&#123;</span><br><span class="line">			<span class="keyword">return</span> <span class="type">_t</span>.<span class="built_in">begin</span>();</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="function">const_iterator <span class="title">end</span><span class="params">()</span> <span class="type">const</span></span></span><br><span class="line"><span class="function">		</span>&#123;</span><br><span class="line">			<span class="keyword">return</span> <span class="type">_t</span>.<span class="built_in">end</span>();</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="comment">// iterator RBTree::const_iterator</span></span><br><span class="line">		<span class="function">pair&lt;iterator, <span class="type">bool</span>&gt; <span class="title">insert</span><span class="params">(<span class="type">const</span> K&amp; key)</span></span></span><br><span class="line"><span class="function">		</span>&#123;</span><br><span class="line">			<span class="comment">// pair&lt;RBTree::iterator, bool&gt;</span></span><br><span class="line">			pair&lt;<span class="keyword">typename</span> RBTree&lt;K, K, SetKeyOfT&gt;::iterator, <span class="type">bool</span>&gt; ret = <span class="type">_t</span>.<span class="built_in">Insert</span>(key);</span><br><span class="line">			<span class="keyword">return</span> <span class="built_in">pair</span>&lt;iterator, <span class="type">bool</span>&gt;(ret.first, ret.second);</span><br><span class="line">		&#125;</span><br><span class="line">	<span class="keyword">private</span>:</span><br><span class="line">		RBTree&lt;K, K, SetKeyOfT&gt; <span class="type">_t</span>;</span><br><span class="line">	&#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>🚩<strong>MyMap.h</strong></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">pragma</span> once</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&quot;RBTree.h&quot;</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">namespace</span> bit</span><br><span class="line">&#123;</span><br><span class="line">	<span class="keyword">template</span>&lt;<span class="keyword">class</span> <span class="title class_">K</span>, <span class="keyword">class</span> <span class="title class_">V</span>&gt;</span><br><span class="line">	<span class="keyword">class</span> <span class="title class_">map</span></span><br><span class="line">	&#123;</span><br><span class="line">		<span class="keyword">struct</span> <span class="title class_">MapKeyOfT</span></span><br><span class="line">		&#123;</span><br><span class="line">			<span class="function"><span class="type">const</span> K&amp; <span class="title">operator</span><span class="params">()</span><span class="params">(<span class="type">const</span> pair&lt;K, V&gt;&amp; kv)</span></span></span><br><span class="line"><span class="function">			</span>&#123;</span><br><span class="line">				<span class="keyword">return</span> kv.first;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;;</span><br><span class="line">	<span class="keyword">public</span>:</span><br><span class="line">		<span class="keyword">typedef</span> <span class="keyword">typename</span> RBTree&lt;K, pair&lt;<span class="type">const</span> K, V&gt;, MapKeyOfT&gt;::iterator iterator;</span><br><span class="line">		<span class="keyword">typedef</span> <span class="keyword">typename</span> RBTree&lt;K, pair&lt;<span class="type">const</span> K, V&gt;, MapKeyOfT&gt;::const_iterator const_iterator;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">		<span class="function">iterator <span class="title">begin</span><span class="params">()</span></span></span><br><span class="line"><span class="function">		</span>&#123;</span><br><span class="line">			<span class="keyword">return</span> <span class="type">_t</span>.<span class="built_in">begin</span>();</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="function">iterator <span class="title">end</span><span class="params">()</span></span></span><br><span class="line"><span class="function">		</span>&#123;</span><br><span class="line">			<span class="keyword">return</span> <span class="type">_t</span>.<span class="built_in">end</span>();</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="function">const_iterator <span class="title">begin</span><span class="params">()</span> <span class="type">const</span></span></span><br><span class="line"><span class="function">		</span>&#123;</span><br><span class="line">			<span class="keyword">return</span> <span class="type">_t</span>.<span class="built_in">begin</span>();</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="function">const_iterator <span class="title">end</span><span class="params">()</span> <span class="type">const</span></span></span><br><span class="line"><span class="function">		</span>&#123;</span><br><span class="line">			<span class="keyword">return</span> <span class="type">_t</span>.<span class="built_in">end</span>();</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		V&amp; <span class="keyword">operator</span>[](<span class="type">const</span> K&amp; key)</span><br><span class="line">		&#123;</span><br><span class="line">			pair&lt;iterator, <span class="type">bool</span>&gt; ret = <span class="built_in">insert</span>(<span class="built_in">make_pair</span>(key, <span class="built_in">V</span>()));</span><br><span class="line">			<span class="keyword">return</span> ret.first-&gt;second;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="function">pair&lt;iterator, <span class="type">bool</span>&gt; <span class="title">insert</span><span class="params">(<span class="type">const</span> pair&lt;K, V&gt;&amp; kv)</span></span></span><br><span class="line"><span class="function">		</span>&#123;</span><br><span class="line">			<span class="keyword">return</span> <span class="type">_t</span>.<span class="built_in">Insert</span>(kv);</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">private</span>:</span><br><span class="line">		RBTree&lt;K, pair&lt;<span class="type">const</span> K, V&gt;, MapKeyOfT&gt; <span class="type">_t</span>;</span><br><span class="line">	&#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>🚩<strong>RBTree.h</strong></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br><span class="line">267</span><br><span class="line">268</span><br><span class="line">269</span><br><span class="line">270</span><br><span class="line">271</span><br><span class="line">272</span><br><span class="line">273</span><br><span class="line">274</span><br><span class="line">275</span><br><span class="line">276</span><br><span class="line">277</span><br><span class="line">278</span><br><span class="line">279</span><br><span class="line">280</span><br><span class="line">281</span><br><span class="line">282</span><br><span class="line">283</span><br><span class="line">284</span><br><span class="line">285</span><br><span class="line">286</span><br><span class="line">287</span><br><span class="line">288</span><br><span class="line">289</span><br><span class="line">290</span><br><span class="line">291</span><br><span class="line">292</span><br><span class="line">293</span><br><span class="line">294</span><br><span class="line">295</span><br><span class="line">296</span><br><span class="line">297</span><br><span class="line">298</span><br><span class="line">299</span><br><span class="line">300</span><br><span class="line">301</span><br><span class="line">302</span><br><span class="line">303</span><br><span class="line">304</span><br><span class="line">305</span><br><span class="line">306</span><br><span class="line">307</span><br><span class="line">308</span><br><span class="line">309</span><br><span class="line">310</span><br><span class="line">311</span><br><span class="line">312</span><br><span class="line">313</span><br><span class="line">314</span><br><span class="line">315</span><br><span class="line">316</span><br><span class="line">317</span><br><span class="line">318</span><br><span class="line">319</span><br><span class="line">320</span><br><span class="line">321</span><br><span class="line">322</span><br><span class="line">323</span><br><span class="line">324</span><br><span class="line">325</span><br><span class="line">326</span><br><span class="line">327</span><br><span class="line">328</span><br><span class="line">329</span><br><span class="line">330</span><br><span class="line">331</span><br><span class="line">332</span><br><span class="line">333</span><br><span class="line">334</span><br><span class="line">335</span><br><span class="line">336</span><br><span class="line">337</span><br><span class="line">338</span><br><span class="line">339</span><br><span class="line">340</span><br><span class="line">341</span><br><span class="line">342</span><br><span class="line">343</span><br><span class="line">344</span><br><span class="line">345</span><br><span class="line">346</span><br><span class="line">347</span><br><span class="line">348</span><br><span class="line">349</span><br><span class="line">350</span><br><span class="line">351</span><br><span class="line">352</span><br><span class="line">353</span><br><span class="line">354</span><br><span class="line">355</span><br><span class="line">356</span><br><span class="line">357</span><br><span class="line">358</span><br><span class="line">359</span><br><span class="line">360</span><br><span class="line">361</span><br><span class="line">362</span><br><span class="line">363</span><br><span class="line">364</span><br><span class="line">365</span><br><span class="line">366</span><br><span class="line">367</span><br><span class="line">368</span><br><span class="line">369</span><br><span class="line">370</span><br><span class="line">371</span><br><span class="line">372</span><br><span class="line">373</span><br><span class="line">374</span><br><span class="line">375</span><br><span class="line">376</span><br><span class="line">377</span><br><span class="line">378</span><br><span class="line">379</span><br><span class="line">380</span><br><span class="line">381</span><br><span class="line">382</span><br><span class="line">383</span><br><span class="line">384</span><br><span class="line">385</span><br><span class="line">386</span><br><span class="line">387</span><br><span class="line">388</span><br><span class="line">389</span><br><span class="line">390</span><br><span class="line">391</span><br><span class="line">392</span><br><span class="line">393</span><br><span class="line">394</span><br><span class="line">395</span><br><span class="line">396</span><br><span class="line">397</span><br><span class="line">398</span><br><span class="line">399</span><br><span class="line">400</span><br><span class="line">401</span><br><span class="line">402</span><br><span class="line">403</span><br><span class="line">404</span><br><span class="line">405</span><br><span class="line">406</span><br><span class="line">407</span><br><span class="line">408</span><br><span class="line">409</span><br><span class="line">410</span><br><span class="line">411</span><br><span class="line">412</span><br><span class="line">413</span><br><span class="line">414</span><br><span class="line">415</span><br><span class="line">416</span><br><span class="line">417</span><br><span class="line">418</span><br><span class="line">419</span><br><span class="line">420</span><br><span class="line">421</span><br><span class="line">422</span><br><span class="line">423</span><br><span class="line">424</span><br><span class="line">425</span><br><span class="line">426</span><br><span class="line">427</span><br><span class="line">428</span><br><span class="line">429</span><br><span class="line">430</span><br><span class="line">431</span><br><span class="line">432</span><br><span class="line">433</span><br><span class="line">434</span><br><span class="line">435</span><br><span class="line">436</span><br><span class="line">437</span><br><span class="line">438</span><br><span class="line">439</span><br><span class="line">440</span><br><span class="line">441</span><br><span class="line">442</span><br><span class="line">443</span><br><span class="line">444</span><br><span class="line">445</span><br><span class="line">446</span><br><span class="line">447</span><br><span class="line">448</span><br><span class="line">449</span><br><span class="line">450</span><br><span class="line">451</span><br><span class="line">452</span><br><span class="line">453</span><br><span class="line">454</span><br><span class="line">455</span><br><span class="line">456</span><br><span class="line">457</span><br><span class="line">458</span><br><span class="line">459</span><br><span class="line">460</span><br><span class="line">461</span><br><span class="line">462</span><br><span class="line">463</span><br><span class="line">464</span><br><span class="line">465</span><br><span class="line">466</span><br><span class="line">467</span><br><span class="line">468</span><br><span class="line">469</span><br><span class="line">470</span><br><span class="line">471</span><br><span class="line">472</span><br><span class="line">473</span><br><span class="line">474</span><br><span class="line">475</span><br><span class="line">476</span><br><span class="line">477</span><br><span class="line">478</span><br><span class="line">479</span><br><span class="line">480</span><br><span class="line">481</span><br><span class="line">482</span><br><span class="line">483</span><br><span class="line">484</span><br><span class="line">485</span><br><span class="line">486</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">pragma</span> once</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line"></span><br><span class="line"><span class="keyword">enum</span> <span class="title class_">Colour</span></span><br><span class="line">&#123;</span><br><span class="line">	RED,</span><br><span class="line">	BLACK</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">template</span>&lt;<span class="keyword">class</span> <span class="title class_">T</span>&gt;</span><br><span class="line"><span class="keyword">struct</span> <span class="title class_">RBTreeNode</span></span><br><span class="line">&#123;</span><br><span class="line">	RBTreeNode&lt;T&gt;* _left;</span><br><span class="line">	RBTreeNode&lt;T&gt;* _right;</span><br><span class="line">	RBTreeNode&lt;T&gt;* _parent;</span><br><span class="line"></span><br><span class="line">	T _data;</span><br><span class="line">	Colour _col;</span><br><span class="line"></span><br><span class="line">	<span class="built_in">RBTreeNode</span>(<span class="type">const</span> T&amp; data)</span><br><span class="line">		:_left(<span class="literal">nullptr</span>)</span><br><span class="line">		, _right(<span class="literal">nullptr</span>)</span><br><span class="line">		, _parent(<span class="literal">nullptr</span>)</span><br><span class="line">		, _data(data)</span><br><span class="line">		, _col(RED)</span><br><span class="line">	&#123;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">template</span>&lt;<span class="keyword">class</span> <span class="title class_">T</span>, <span class="keyword">class</span> <span class="title class_">Ptr</span>, <span class="keyword">class</span> <span class="title class_">Ref</span>&gt;</span><br><span class="line"><span class="keyword">struct</span> <span class="title class_">__TreeIterator</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="keyword">typedef</span> RBTreeNode&lt;T&gt; Node;</span><br><span class="line">	<span class="keyword">typedef</span> __TreeIterator&lt;T, Ptr, Ref&gt; Self;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">typedef</span> __TreeIterator&lt;T, T*, T&amp;&gt; Iterator;</span><br><span class="line"></span><br><span class="line">	__TreeIterator(<span class="type">const</span> Iterator&amp; it)</span><br><span class="line">		:_node(it._node)</span><br><span class="line">	&#123;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	Node* _node;</span><br><span class="line"></span><br><span class="line">	__TreeIterator(Node* node)</span><br><span class="line">		:_node(node)</span><br><span class="line">	&#123;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	Ref <span class="keyword">operator</span>*()</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="keyword">return</span> _node-&gt;_data;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	Ptr <span class="keyword">operator</span>-&gt;()</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="keyword">return</span> &amp;_node-&gt;_data;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="type">bool</span> <span class="keyword">operator</span>!=(<span class="type">const</span> Self&amp; s) <span class="type">const</span></span><br><span class="line">	&#123;</span><br><span class="line">		<span class="keyword">return</span> _node != s._node;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="type">bool</span> <span class="keyword">operator</span>==(<span class="type">const</span> Self&amp; s) <span class="type">const</span></span><br><span class="line">	&#123;</span><br><span class="line">		<span class="keyword">return</span> _node != s._node;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	Self&amp; <span class="keyword">operator</span>--()</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="keyword">if</span> (_node-&gt;_left)</span><br><span class="line">		&#123;</span><br><span class="line">			Node* subRight = _node-&gt;_left;</span><br><span class="line">			<span class="keyword">while</span> (subRight-&gt;_right)</span><br><span class="line">			&#123;</span><br><span class="line">				subRight = subRight-&gt;_right;</span><br><span class="line">			&#125;</span><br><span class="line"></span><br><span class="line">			_node = subRight;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span></span><br><span class="line">		&#123;</span><br><span class="line">			<span class="comment">// 孩子是父亲的右的那个节点</span></span><br><span class="line">			Node* cur = _node;</span><br><span class="line">			Node* parent = cur-&gt;_parent;</span><br><span class="line">			<span class="keyword">while</span> (parent &amp;&amp; cur == parent-&gt;_left)</span><br><span class="line">			&#123;</span><br><span class="line">				cur = cur-&gt;_parent;</span><br><span class="line">				parent = parent-&gt;_parent;</span><br><span class="line">			&#125;</span><br><span class="line"></span><br><span class="line">			_node = parent;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="keyword">return</span> *<span class="keyword">this</span>;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	Self&amp; <span class="keyword">operator</span>++()</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="keyword">if</span> (_node-&gt;_right)</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="comment">// 右树的最左节点(最小节点)</span></span><br><span class="line">			Node* subLeft = _node-&gt;_right;</span><br><span class="line">			<span class="keyword">while</span> (subLeft-&gt;_left)</span><br><span class="line">			&#123;</span><br><span class="line">				subLeft = subLeft-&gt;_left;</span><br><span class="line">			&#125;</span><br><span class="line"></span><br><span class="line">			_node = subLeft;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span></span><br><span class="line">		&#123;</span><br><span class="line">			Node* cur = _node;</span><br><span class="line">			Node* parent = cur-&gt;_parent;</span><br><span class="line">			<span class="comment">// 找孩子是父亲左的那个祖先节点，就是下一个要访问的节点</span></span><br><span class="line">			<span class="keyword">while</span> (parent &amp;&amp; cur == parent-&gt;_right)</span><br><span class="line">			&#123;</span><br><span class="line">				cur = cur-&gt;_parent;</span><br><span class="line">				parent = parent-&gt;_parent;</span><br><span class="line">			&#125;</span><br><span class="line"></span><br><span class="line">			_node = parent;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="keyword">return</span> *<span class="keyword">this</span>;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">// set-&gt;RBTree&lt;K, K, SetKeyOfT&gt; _t;</span></span><br><span class="line"><span class="comment">// map-&gt;RBTree&lt;K, pair&lt;K, V&gt;, MapKeyOfT&gt; _t;</span></span><br><span class="line"><span class="keyword">template</span>&lt;<span class="keyword">class</span> <span class="title class_">K</span>, <span class="keyword">class</span> <span class="title class_">T</span>, <span class="keyword">class</span> <span class="title class_">KeyOfT</span>&gt;</span><br><span class="line"><span class="keyword">struct</span> <span class="title class_">RBTree</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="keyword">typedef</span> RBTreeNode&lt;T&gt; Node;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="comment">// 同一个类模板，传的不同的参数实例化出的不同类型</span></span><br><span class="line">	<span class="keyword">typedef</span> __TreeIterator&lt;T, T*, T&amp;&gt; iterator;</span><br><span class="line">	<span class="keyword">typedef</span> __TreeIterator&lt;T, <span class="type">const</span> T*, <span class="type">const</span> T&amp;&gt; const_iterator;</span><br><span class="line"></span><br><span class="line">	<span class="function">iterator <span class="title">begin</span><span class="params">()</span></span></span><br><span class="line"><span class="function">	</span>&#123;</span><br><span class="line">		Node* leftMin = _root;</span><br><span class="line">		<span class="keyword">while</span> (leftMin &amp;&amp; leftMin-&gt;_left)</span><br><span class="line">		&#123;</span><br><span class="line">			leftMin = leftMin-&gt;_left;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="keyword">return</span> <span class="built_in">iterator</span>(leftMin);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function">iterator <span class="title">end</span><span class="params">()</span></span></span><br><span class="line"><span class="function">	</span>&#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="built_in">iterator</span>(<span class="literal">nullptr</span>);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function">const_iterator <span class="title">begin</span><span class="params">()</span> <span class="type">const</span></span></span><br><span class="line"><span class="function">	</span>&#123;</span><br><span class="line">		Node* leftMin = _root;</span><br><span class="line">		<span class="keyword">while</span> (leftMin &amp;&amp; leftMin-&gt;_left)</span><br><span class="line">		&#123;</span><br><span class="line">			leftMin = leftMin-&gt;_left;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="keyword">return</span> <span class="built_in">const_iterator</span>(leftMin);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function">const_iterator <span class="title">end</span><span class="params">()</span> <span class="type">const</span></span></span><br><span class="line"><span class="function">	</span>&#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="built_in">const_iterator</span>(<span class="literal">nullptr</span>);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function">Node* <span class="title">Find</span><span class="params">(<span class="type">const</span> K&amp; key)</span></span></span><br><span class="line"><span class="function">	</span>&#123;</span><br><span class="line">		Node* cur = _root;</span><br><span class="line">		KeyOfT kot;</span><br><span class="line">		<span class="keyword">while</span> (cur)</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="keyword">if</span> (<span class="built_in">kot</span>(cur-&gt;_data) &lt; key)</span><br><span class="line">			&#123;</span><br><span class="line">				cur = cur-&gt;_right;</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">else</span> <span class="keyword">if</span> (<span class="built_in">kot</span>(cur-&gt;_data) &gt; key)</span><br><span class="line">			&#123;</span><br><span class="line">				cur = cur-&gt;_left;</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">else</span></span><br><span class="line">			&#123;</span><br><span class="line">				<span class="keyword">return</span> cur;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="keyword">return</span> <span class="literal">nullptr</span>;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function">pair&lt;iterator, <span class="type">bool</span>&gt; <span class="title">Insert</span><span class="params">(<span class="type">const</span> T&amp; data)</span></span></span><br><span class="line"><span class="function">	</span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (_root == <span class="literal">nullptr</span>)</span><br><span class="line">		&#123;</span><br><span class="line">			_root = <span class="keyword">new</span> <span class="built_in">Node</span>(data);</span><br><span class="line">			_root-&gt;_col = BLACK;</span><br><span class="line">			<span class="keyword">return</span> <span class="built_in">make_pair</span>(<span class="built_in">iterator</span>(_root), <span class="literal">true</span>);</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		Node* parent = <span class="literal">nullptr</span>;</span><br><span class="line">		Node* cur = _root;</span><br><span class="line"></span><br><span class="line">		KeyOfT kot;</span><br><span class="line">		<span class="keyword">while</span> (cur)</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="keyword">if</span> (<span class="built_in">kot</span>(cur-&gt;_data) &lt; <span class="built_in">kot</span>(data))</span><br><span class="line">			&#123;</span><br><span class="line">				parent = cur;</span><br><span class="line">				cur = cur-&gt;_right;</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">else</span> <span class="keyword">if</span> (<span class="built_in">kot</span>(cur-&gt;_data) &gt; <span class="built_in">kot</span>(data))</span><br><span class="line">			&#123;</span><br><span class="line">				parent = cur;</span><br><span class="line">				cur = cur-&gt;_left;</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">else</span></span><br><span class="line">			&#123;</span><br><span class="line">				<span class="keyword">return</span> <span class="built_in">make_pair</span>(<span class="built_in">iterator</span>(cur), <span class="literal">false</span>);</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		cur = <span class="keyword">new</span> <span class="built_in">Node</span>(data);</span><br><span class="line">		cur-&gt;_col = RED;</span><br><span class="line"></span><br><span class="line">		Node* newnode = cur;</span><br><span class="line"></span><br><span class="line">		<span class="keyword">if</span> (<span class="built_in">kot</span>(parent-&gt;_data) &lt; <span class="built_in">kot</span>(data))</span><br><span class="line">		&#123;</span><br><span class="line">			parent-&gt;_right = cur;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span></span><br><span class="line">		&#123;</span><br><span class="line">			parent-&gt;_left = cur;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		cur-&gt;_parent = parent;</span><br><span class="line"></span><br><span class="line">		<span class="keyword">while</span> (parent &amp;&amp; parent-&gt;_col == RED)</span><br><span class="line">		&#123;</span><br><span class="line">			Node* grandfather = parent-&gt;_parent;</span><br><span class="line">			<span class="keyword">if</span> (parent == grandfather-&gt;_left)</span><br><span class="line">			&#123;</span><br><span class="line">				Node* uncle = grandfather-&gt;_right;</span><br><span class="line">				<span class="comment">// u存在且为红</span></span><br><span class="line">				<span class="keyword">if</span> (uncle &amp;&amp; uncle-&gt;_col == RED)</span><br><span class="line">				&#123;</span><br><span class="line">					<span class="comment">// 变色</span></span><br><span class="line">					parent-&gt;_col = uncle-&gt;_col = BLACK;</span><br><span class="line">					grandfather-&gt;_col = RED;</span><br><span class="line"></span><br><span class="line">					<span class="comment">// 继续向上处理</span></span><br><span class="line">					cur = grandfather;</span><br><span class="line">					parent = cur-&gt;_parent;</span><br><span class="line">				&#125;</span><br><span class="line">				<span class="keyword">else</span> <span class="comment">// u不存在 或 存在且为黑</span></span><br><span class="line">				&#123;</span><br><span class="line">					<span class="keyword">if</span> (cur == parent-&gt;_left)</span><br><span class="line">					&#123;</span><br><span class="line">						<span class="comment">//     g</span></span><br><span class="line">						<span class="comment">//   p</span></span><br><span class="line">						<span class="comment">// c</span></span><br><span class="line">						<span class="built_in">RotateR</span>(grandfather);</span><br><span class="line">						parent-&gt;_col = BLACK;</span><br><span class="line">						grandfather-&gt;_col = RED;</span><br><span class="line">					&#125;</span><br><span class="line">					<span class="keyword">else</span></span><br><span class="line">					&#123;</span><br><span class="line">						<span class="comment">//     g</span></span><br><span class="line">						<span class="comment">//   p</span></span><br><span class="line">						<span class="comment">//		c</span></span><br><span class="line">						<span class="built_in">RotateL</span>(parent);</span><br><span class="line">						<span class="built_in">RotateR</span>(grandfather);</span><br><span class="line"></span><br><span class="line">						cur-&gt;_col = BLACK;</span><br><span class="line">						grandfather-&gt;_col = RED;</span><br><span class="line">					&#125;</span><br><span class="line"></span><br><span class="line">					<span class="keyword">break</span>;</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">else</span> <span class="comment">// parent == grandfather-&gt;_right</span></span><br><span class="line">			&#123;</span><br><span class="line">				Node* uncle = grandfather-&gt;_left;</span><br><span class="line">				<span class="comment">// u存在且为红</span></span><br><span class="line">				<span class="keyword">if</span> (uncle &amp;&amp; uncle-&gt;_col == RED)</span><br><span class="line">				&#123;</span><br><span class="line">					<span class="comment">// 变色</span></span><br><span class="line">					parent-&gt;_col = uncle-&gt;_col = BLACK;</span><br><span class="line">					grandfather-&gt;_col = RED;</span><br><span class="line"></span><br><span class="line">					<span class="comment">// 继续向上处理</span></span><br><span class="line">					cur = grandfather;</span><br><span class="line">					parent = cur-&gt;_parent;</span><br><span class="line">				&#125;</span><br><span class="line">				<span class="keyword">else</span></span><br><span class="line">				&#123;</span><br><span class="line">					<span class="keyword">if</span> (cur == parent-&gt;_right)</span><br><span class="line">					&#123;</span><br><span class="line">						<span class="comment">// g</span></span><br><span class="line">						<span class="comment">//	  p</span></span><br><span class="line">						<span class="comment">//       c</span></span><br><span class="line">						<span class="built_in">RotateL</span>(grandfather);</span><br><span class="line">						grandfather-&gt;_col = RED;</span><br><span class="line">						parent-&gt;_col = BLACK;</span><br><span class="line">					&#125;</span><br><span class="line">					<span class="keyword">else</span></span><br><span class="line">					&#123;</span><br><span class="line">						<span class="comment">// g</span></span><br><span class="line">						<span class="comment">//	  p</span></span><br><span class="line">						<span class="comment">// c</span></span><br><span class="line">						<span class="built_in">RotateR</span>(parent);</span><br><span class="line">						<span class="built_in">RotateL</span>(grandfather);</span><br><span class="line">						cur-&gt;_col = BLACK;</span><br><span class="line">						grandfather-&gt;_col = RED;</span><br><span class="line">					&#125;</span><br><span class="line"></span><br><span class="line">					<span class="keyword">break</span>;</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		_root-&gt;_col = BLACK;</span><br><span class="line"></span><br><span class="line">		<span class="keyword">return</span> <span class="built_in">make_pair</span>(<span class="built_in">iterator</span>(newnode), <span class="literal">true</span>);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="type">void</span> <span class="title">RotateL</span><span class="params">(Node* parent)</span></span></span><br><span class="line"><span class="function">	</span>&#123;</span><br><span class="line">		++_rotateCount;</span><br><span class="line"></span><br><span class="line">		Node* cur = parent-&gt;_right;</span><br><span class="line">		Node* curleft = cur-&gt;_left;</span><br><span class="line"></span><br><span class="line">		parent-&gt;_right = curleft;</span><br><span class="line">		<span class="keyword">if</span> (curleft)</span><br><span class="line">		&#123;</span><br><span class="line">			curleft-&gt;_parent = parent;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		cur-&gt;_left = parent;</span><br><span class="line"></span><br><span class="line">		Node* ppnode = parent-&gt;_parent;</span><br><span class="line"></span><br><span class="line">		parent-&gt;_parent = cur;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">		<span class="keyword">if</span> (parent == _root)</span><br><span class="line">		&#123;</span><br><span class="line">			_root = cur;</span><br><span class="line">			cur-&gt;_parent = <span class="literal">nullptr</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span></span><br><span class="line">		&#123;</span><br><span class="line">			<span class="keyword">if</span> (ppnode-&gt;_left == parent)</span><br><span class="line">			&#123;</span><br><span class="line">				ppnode-&gt;_left = cur;</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">else</span></span><br><span class="line">			&#123;</span><br><span class="line">				ppnode-&gt;_right = cur;</span><br><span class="line"></span><br><span class="line">			&#125;</span><br><span class="line"></span><br><span class="line">			cur-&gt;_parent = ppnode;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="type">void</span> <span class="title">RotateR</span><span class="params">(Node* parent)</span></span></span><br><span class="line"><span class="function">	</span>&#123;</span><br><span class="line">		++_rotateCount;</span><br><span class="line"></span><br><span class="line">		Node* cur = parent-&gt;_left;</span><br><span class="line">		Node* curright = cur-&gt;_right;</span><br><span class="line"></span><br><span class="line">		parent-&gt;_left = curright;</span><br><span class="line">		<span class="keyword">if</span> (curright)</span><br><span class="line">			curright-&gt;_parent = parent;</span><br><span class="line"></span><br><span class="line">		Node* ppnode = parent-&gt;_parent;</span><br><span class="line">		cur-&gt;_right = parent;</span><br><span class="line">		parent-&gt;_parent = cur;</span><br><span class="line"></span><br><span class="line">		<span class="keyword">if</span> (ppnode == <span class="literal">nullptr</span>)</span><br><span class="line">		&#123;</span><br><span class="line">			_root = cur;</span><br><span class="line">			cur-&gt;_parent = <span class="literal">nullptr</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span></span><br><span class="line">		&#123;</span><br><span class="line">			<span class="keyword">if</span> (ppnode-&gt;_left == parent)</span><br><span class="line">			&#123;</span><br><span class="line">				ppnode-&gt;_left = cur;</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">else</span></span><br><span class="line">			&#123;</span><br><span class="line">				ppnode-&gt;_right = cur;</span><br><span class="line">			&#125;</span><br><span class="line"></span><br><span class="line">			cur-&gt;_parent = ppnode;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 17:20继续</span></span><br><span class="line">	<span class="function"><span class="type">bool</span> <span class="title">CheckColour</span><span class="params">(Node* root, <span class="type">int</span> blacknum, <span class="type">int</span> benchmark)</span></span></span><br><span class="line"><span class="function">	</span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (root == <span class="literal">nullptr</span>)</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="keyword">if</span> (blacknum != benchmark)</span><br><span class="line">				<span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line"></span><br><span class="line">			<span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="keyword">if</span> (root-&gt;_col == BLACK)</span><br><span class="line">		&#123;</span><br><span class="line">			++blacknum;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="keyword">if</span> (root-&gt;_col == RED &amp;&amp; root-&gt;_parent &amp;&amp; root-&gt;_parent-&gt;_col == RED)</span><br><span class="line">		&#123;</span><br><span class="line">			cout &lt;&lt; root-&gt;_kv.first &lt;&lt; <span class="string">&quot;出现连续红色节点&quot;</span> &lt;&lt; endl;</span><br><span class="line">			<span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="keyword">return</span> <span class="built_in">CheckColour</span>(root-&gt;_left, blacknum, benchmark)</span><br><span class="line">			&amp;&amp; <span class="built_in">CheckColour</span>(root-&gt;_right, blacknum, benchmark);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="type">bool</span> <span class="title">IsBalance</span><span class="params">()</span></span></span><br><span class="line"><span class="function">	</span>&#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="built_in">IsBalance</span>(_root);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="type">bool</span> <span class="title">IsBalance</span><span class="params">(Node* root)</span></span></span><br><span class="line"><span class="function">	</span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (root == <span class="literal">nullptr</span>)</span><br><span class="line">			<span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line"></span><br><span class="line">		<span class="keyword">if</span> (root-&gt;_col != BLACK)</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="comment">// 基准值</span></span><br><span class="line">		<span class="type">int</span> benchmark = <span class="number">0</span>;</span><br><span class="line">		Node* cur = _root;</span><br><span class="line">		<span class="keyword">while</span> (cur)</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="keyword">if</span> (cur-&gt;_col == BLACK)</span><br><span class="line">				++benchmark;</span><br><span class="line"></span><br><span class="line">			cur = cur-&gt;_left;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="keyword">return</span> <span class="built_in">CheckColour</span>(root, <span class="number">0</span>, benchmark);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="type">int</span> <span class="title">Height</span><span class="params">()</span></span></span><br><span class="line"><span class="function">	</span>&#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="built_in">Height</span>(_root);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="type">int</span> <span class="title">Height</span><span class="params">(Node* root)</span></span></span><br><span class="line"><span class="function">	</span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (root == <span class="literal">nullptr</span>)</span><br><span class="line">			<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">		<span class="type">int</span> leftHeight = <span class="built_in">Height</span>(root-&gt;_left);</span><br><span class="line">		<span class="type">int</span> rightHeight = <span class="built_in">Height</span>(root-&gt;_right);</span><br><span class="line"></span><br><span class="line">		<span class="keyword">return</span> leftHeight &gt; rightHeight ? leftHeight + <span class="number">1</span> : rightHeight + <span class="number">1</span>;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">	Node* _root = <span class="literal">nullptr</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="type">int</span> _rotateCount = <span class="number">0</span>;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<hr>
<h1 id="希望读者们多多三连支持"><a href="#希望读者们多多三连支持" class="headerlink" title="希望读者们多多三连支持"></a>希望读者们多多三连支持</h1><h1 id="小编会继续更新"><a href="#小编会继续更新" class="headerlink" title="小编会继续更新"></a>小编会继续更新</h1><h1 id="你们的鼓励就是我前进的动力！"><a href="#你们的鼓励就是我前进的动力！" class="headerlink" title="你们的鼓励就是我前进的动力！"></a>你们的鼓励就是我前进的动力！</h1><p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/1a02acd6cb13427a80574da2d4c02983.gif" alt="请添加图片描述"></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="http://example.com">澪贰</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="http://example.com/2025/05/14/CPP%E8%BF%9B%E9%98%B6/map%20&amp;&amp;%20set%E5%BA%95%E5%B1%82%E5%89%96%E6%9E%90%E5%8F%8A%E8%BF%AD%E4%BB%A3%E5%99%A8%E4%B8%87%E5%AD%97%E8%AF%A6%E8%A7%A3/">http://example.com/2025/05/14/CPP进阶/map &amp;&amp; set底层剖析及迭代器万字详解/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来源 <a href="http://example.com" target="_blank">澪贰</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/C/">C++</a><a class="post-meta__tags" href="/tags/stl/">stl</a><a class="post-meta__tags" href="/tags/map/">map</a><a class="post-meta__tags" href="/tags/set/">set</a></div><div class="post-share"><div class="social-share" data-image="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250511012240.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i>赞助</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/Wechat.png" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/Wechat.png" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/Alipay.png" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/Alipay.png" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><a class="pagination-related" href="/2025/05/19/CPP%E8%BF%9B%E9%98%B6/%E5%93%88%E5%B8%8C/" title="C++寻位映射的奇幻密码：哈希"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250514225818.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="info"><div class="info-1"><div class="info-item-1">上一篇</div><div class="info-item-2">C++寻位映射的奇幻密码：哈希</div></div><div class="info-2"><div class="info-item-1">哈希，用于将任意大小的数据映射为固定长度的数值（哈希值），这个过程通过哈希函数实现，其核心目标是高效地存储、查找和验证数据 什么是哈希？ 在学哈希之前，我们对于数据的查找通常是建立于顺序表，树形结构的基础上进行的查找，但是随着数据量越来越庞大，数据的随机性和容量越发严峻 理想的搜索方法： 可以不经过任何比较，一次直接从表中得到要搜索的元素如果构造一种存储结构，通过某种函数( hashFunc )使元素的存储位置与它的关键码之间能够建立一一映射的关系，那么在查找时通过该函数可以很快找到该元素 因此就在此基础上发展出了一种平均时间复杂度几乎为 O(1) 的数据查找方式，哈希，也称为散列 哈希的常见实现方法直接定址法 对于一段相对集中的数据段，就可以使用直接定址法，这里最大的数是 30，最小的数是15，创建一个大小为 15 的数组，将所有值映射到数组上 优点： 简单、均匀缺点： 需要事先知道关键字的分布情况使用场景：...</div></div></div></a><a class="pagination-related" href="/2025/05/12/CPP%E8%BF%9B%E9%98%B6/%E7%BA%A2%E9%BB%91%E6%A0%91/" title="C++色彩博弈的史诗：红黑树"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250507163801.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="info text-right"><div class="info-1"><div class="info-item-1">下一篇</div><div class="info-item-2">C++色彩博弈的史诗：红黑树</div></div><div class="info-2"><div class="info-item-1">红黑树是一种自平衡二叉查找树，每个节点都带有颜色属性，颜色或为红色或为黑色，可以理解为 AVL 树的进阶版，建议系统学习完 AVL 树再来看本篇博客  传送门：C++漫步结构与平衡的殿堂：AVL树  红黑树的概念  红黑树，是一种二叉搜索树，但在每个结点上增加一个存储位表示结点的颜色，可以是 Red 或 Black。 通过对任何一条从根到叶子的路径上各个结点着色方式的限制，红黑树确保最长路径的节点数量不超过最短路径节点数量的两倍（刚好两倍是可以的），因而是接近平衡的  一个合格的红黑树需要满足以下条件：  每个结点不是红色就是黑色  根节点是黑色的   如果一个节点是红色的，则它的两个孩子结点必须是黑色的，任何路径都没有连续的红色节点，也就是说可以有连续的黑色节点，但不可能一颗红黑树全是黑色节点 ...</div></div></div></a></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><a class="pagination-related" href="/2025/05/01/CPP%E8%BF%9B%E9%98%B6/map%20&&%20set/" title="C++漫溯键值的长河：map &amp;&amp; set"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250714103009.png" alt="cover"><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-05-01</div><div class="info-item-2">C++漫溯键值的长河：map &amp;&amp; set</div></div><div class="info-2"><div class="info-item-1">迄今为止，除了二叉搜索树以外的结构，我们学习到的顺序表，链表，栈和队列等都属于这些容器统称为序列式容器，因为其底层为线性序列的数据结构，里面存储的是元素本身 关联式容器 根据应用场景的不同，STL 总共实现了两种不同结构的管理式容器：树型结构与哈希结构。树型结构的关联式容器主要有四种：map、set、multimap、multiset。这四种容器的共同点是：使用平衡搜索树(即红黑树)作为其底层结果，容器中的元素是一个有序的序列  关联式容器也是用来存储数据的，与序列式容器不同的是，其里面存储的是&lt;key, value&gt;结构的键值对，在数据检索时比序列式容器效率更高 键对值中的 key 表示键值，value 表示与 key 对应的信息 SGI-STL中关于键值对的定义： 12345678910111213template &lt;class T1, class T2&gt;struct pair&#123;	typedef T1 first_type;	typedef T2 second_type;	T1 first;	T2 second;	pair() :...</div></div></div></a><a class="pagination-related" href="/2025/02/19/CPP%E5%88%9D%E9%98%B6/list%E5%87%BD%E6%95%B0%E5%85%A8%E8%A7%A3/" title="C++效率掌握之STL库：list函数全解"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250218155357.jpg" alt="cover"><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-02-19</div><div class="info-item-2">C++效率掌握之STL库：list函数全解</div></div><div class="info-2"><div class="info-item-1">为什么要学习list？什么是list？ list 是 C++ 标准模板库中的一个容器，它实现了双向链表的数据结构。双向链表由一系列节点组成，每个节点包含一个数据元素和两个指针，分别指向前一个节点和后一个节点。在链表的任意位置进行插入和删除操作的时间复杂度都是O(1) 。这使得它在需要频繁插入和删除元素的场景下表现出色，比如实现一个任务调度器，需要不断地添加新任务、移除已完成的任务  list 也是一种很常用的容器，对于链表的处理提供了极大的便利性  list 的主要特征可总结为：  list 是可以在常数范围内在任意位置进行插入和删除的序列式容器，并且该容器可以前后双向迭代 list 的底层是双向链表结构，双向链表中每个元素存储在互不相关的独立节点中，在节点中通过指针指向其前一个元素和后一个元素 list 与 forward_list 非常相似：最主要的不同在于 forward_list 是单链表，只能朝前迭代，已让其更简单高效 与其他的序列式容器相比(array，vector，deque)，list...</div></div></div></a><a class="pagination-related" href="/2025/03/24/CPP%E5%88%9D%E9%98%B6/stack%20&&%20queue%E5%87%BD%E6%95%B0%E5%85%A8%E8%A7%A3/" title="C++效率掌握之STL库：stack &amp;&amp; queue函数全解"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/2a5f5e9a1b71bd497c24494fbc8e93f.png" alt="cover"><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-03-24</div><div class="info-item-2">C++效率掌握之STL库：stack &amp;&amp; queue函数全解</div></div><div class="info-2"><div class="info-item-1">本篇是 STL 库专题之 stack 和 queue，本质就是栈和队列，关于该数据结构在初阶数据结构专栏里有详细的解释分析，本篇文章主要针对 stack 和 queue 的使用及拓展进行练习和介绍，建议熟悉好相关的数据结构知识再进行本篇学习  传送门：【初阶数据结构】先来后到的秩序：栈和队列  stack stack 的主要特征可总结为：  stack 是一种容器适配器，专门用在具有后进先出操作的上下文环境中，其删除只能从容器的一端进行元素的插入与提取操作 stack 是作为容器适配器被实现的，容器适配器即是对特定类封装作为其底层的容器，并提供一组特定的成员函数来访问其元素，将特定类作为其底层的，元素特定容器的尾部(即栈顶)被压入和弹出 stack 的底层容器可以是任何标准的容器类模板或者一些其他特定的容器类，这些容器类应该支持以下操作：   empty：判空操作 back：获取尾部元素操作 push_back：尾部插入元素操作 pop_back：尾部删除元素操作   标准容器 vector、deque、list 均符合这些需求，默认情况下，如果没有为 stack...</div></div></div></a><a class="pagination-related" href="/2025/02/04/CPP%E5%88%9D%E9%98%B6/string%E5%87%BD%E6%95%B0%E5%85%A8%E8%A7%A3/" title="C++效率掌握之STL库：string函数全解"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250203201429.jpg" alt="cover"><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-02-04</div><div class="info-item-2">C++效率掌握之STL库：string函数全解</div></div><div class="info-2"><div class="info-item-1">为什么要学习string？什么是string？ C语言中，字符串是以’\0’结尾的一些字符的集合，为了操作方便，C标准库中提供了一些str系列的库函数，但是这些库函数与字符串是分离开的，不太符合OOP的思想，而且底层空间需要用户自己管理，稍不留神可能还会越界访问  因此创建了string类，比STL库还要早出现，所以有一定的缺陷和冗余  string的主要特征可总结为：  字符串是表示字符序列的类 该类的接口与常规容器的接口基本相同，再添加了一些专门用来操作string的常规操作 string在底层实际是：basic_string模板类的别名typedef basic_string&lt;char, char_traits, allocator&gt;...</div></div></div></a><a class="pagination-related" href="/2025/02/15/CPP%E5%88%9D%E9%98%B6/string%E5%BA%95%E5%B1%82%E5%89%96%E6%9E%90/" title="C++效率掌握之STL库：string底层剖析"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/111.jpg" alt="cover"><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-02-15</div><div class="info-item-2">C++效率掌握之STL库：string底层剖析</div></div><div class="info-2"><div class="info-item-1">在学习本专题前，请详细学习有关 string 的使用  传送门：C++效率掌握之STL库：string函数全解  学习string底层的必要性 在 C++ 中，知道 string 是如何以字符数组的形式存储，以及字符串连接、查找等操作的时间复杂度，就可以避免在循环中频繁进行字符串连接操作，因为这可能会导致多次内存重新分配和数据复制，从而影响性能，而是选择更高效的方式，如预先分配足够的空间。同时，理解 string 底层对内存的管理方式，有助于优化内存使用，避免空指针和越界的情况出现  string类对象基本函数实现实现一个类首先先从其基本函数开始，包括构造函数、析构函数、内存管理等  简单实现一个空构造和字符串构造，因为还没写 string 流输出的运算符重载，先将 string 类转成 C 语言风格来输出 🔥值得注意的是： 注意变量声明的顺序要和初始化列表一致，也要注意变量初始化顺序对另一个变量的影响；=运算符重载：自我赋值是指对象在赋值时被赋值给自己，例如 s1 =...</div></div></div></a><a class="pagination-related" href="/2025/02/17/CPP%E5%88%9D%E9%98%B6/vector%E5%87%BD%E6%95%B0%E5%85%A8%E8%A7%A3/" title="C++效率掌握之STL库：vector函数全解"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250208193150.jpg" alt="cover"><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-02-17</div><div class="info-item-2">C++效率掌握之STL库：vector函数全解</div></div><div class="info-2"><div class="info-item-1">为什么要学习vector？什么是vector？ vector 是标准模板库（STL）提供的一个容器类，它是动态数组的一种实现。这意味着它可以像普通数组一样存储一组相同类型的元素，并且能根据需要自动调整自身的大小，例如，你可以创建一个存储整数的 vector，然后不断往里面添加或删除元素，它会自动管理内存空间  vector 类是和 STL 库一起问世的，string 函数是在 STL 库之前创造的，为了一致性简便性，vector 、list 等类都减少了一部分不必要的函数，也将 string 加入了 STL 库  vector 的主要特征可总结为：  vector 是表示可变大小数组的序列容器。 就像数组一样，vector 也采用的连续存储空间来存储元素。也就是意味着可以采用下标对 vector 的元素进行访问，和数组一样高效。但是又不像数组，它的大小是可以动态改变的，而且它的大小会被容器自动处理 本质讲，vector...</div></div></div></a></div></div><hr class="custom-hr"/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="twikoo-wrap"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info text-center"><div class="card-info-avatar"><div class="avatar-img"><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/zero_two.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-status-box"><div class="author-status"><g-emoji class="g-emoji" alias="palm_tree" fallback-src="https://lskypro.acozycotage.net/LightPicture/2022/12/fe1dc0402e623096.jpg">🤯</g-emoji><span>头脑风暴中</span></div></div></div><div class="author-info-name">澪贰</div><div class="author-info-description"></div><div class="site-data"><a href="/archives/"><div class="headline">文章</div><div class="length-num">96</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">74</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">9</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/ZeroCoder-Zhang"><i></i><span>🛫下一站--github</span></a><div class="card-info-social-icons"><a class="social-icon" href="https://github.com/ZeroCoder-Zhang" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a><a class="social-icon" href="mailto:1478943685@qq.com" target="_blank" title="Email"><i class="fas fa-envelope" style="color: #4a7dbe;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content"><center><b>--- 主域名 ---<br><a target="_blank" rel="noopener" href="https://general.zzh-blog.club/" title="主域名链接" class="anno_content"><font color="#5ea6e5">general.zzh-blog.club</font></a></b></center><center><b>--- 推广学习交流(Wechat) ---<br><a target="_blank" rel="noopener" href="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/微信扫码加好友.png" title="微信图片" class="anno_content"><font color="#5ea6e5">zzh1478943685(备注来意)</font></a></b></center></div><div id="welcome-info"></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#map%E3%80%81set%E7%9A%84%E5%9F%BA%E6%9C%AC%E7%BB%93%E6%9E%84"><span class="toc-number">1.</span> <span class="toc-text">map、set的基本结构</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#map%E3%80%81set%E6%A8%A1%E6%8B%9F%E5%AE%9E%E7%8E%B0"><span class="toc-number">2.</span> <span class="toc-text">map、set模拟实现</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%9D%E6%AD%A5%E5%AE%9A%E4%B9%89"><span class="toc-number">2.1.</span> <span class="toc-text">初步定义</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BB%BF%E5%87%BD%E6%95%B0%E5%AE%9E%E7%8E%B0"><span class="toc-number">2.2.</span> <span class="toc-text">仿函数实现</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Find%E5%8A%9F%E8%83%BD%E5%AE%9E%E7%8E%B0"><span class="toc-number">2.3.</span> <span class="toc-text">Find功能实现</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%BF%AD%E4%BB%A3%E5%99%A8%E5%88%9D%E6%AD%A5%E5%8A%9F%E8%83%BD%E5%AE%9E%E7%8E%B0"><span class="toc-number">2.4.</span> <span class="toc-text">迭代器初步功能实现</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%BF%90%E7%AE%97%E7%AC%A6%E9%87%8D%E8%BD%BD"><span class="toc-number">2.4.1.</span> <span class="toc-text">++运算符重载</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E2%80%93%E8%BF%90%E7%AE%97%E7%AC%A6%E9%87%8D%E8%BD%BD"><span class="toc-number">2.4.2.</span> <span class="toc-text">–运算符重载</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%BF%90%E7%AE%97%E7%AC%A6%E9%87%8D%E8%BD%BD-1"><span class="toc-number">2.4.3.</span> <span class="toc-text">*运算符重载</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%BF%90%E7%AE%97%E7%AC%A6%E9%87%8D%E8%BD%BD-2"><span class="toc-number">2.4.4.</span> <span class="toc-text">-&gt;运算符重载</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%BF%90%E7%AE%97%E7%AC%A6%E9%87%8D%E8%BD%BD-3"><span class="toc-number">2.4.5.</span> <span class="toc-text">!&#x3D;运算符重载</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#begin"><span class="toc-number">2.4.6.</span> <span class="toc-text">begin()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#end"><span class="toc-number">2.4.7.</span> <span class="toc-text">end()</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%BF%AD%E4%BB%A3%E5%99%A8%E8%BF%9B%E9%98%B6%E5%8A%9F%E8%83%BD%E5%AE%9E%E7%8E%B0"><span class="toc-number">2.5.</span> <span class="toc-text">迭代器进阶功能实现</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#set%EF%BC%9Aconst%E8%BF%AD%E4%BB%A3%E5%99%A8%E5%8F%8Ainsert%E7%9A%84%E5%AE%9E%E7%8E%B0"><span class="toc-number">2.5.1.</span> <span class="toc-text">set：const迭代器及insert的实现</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#map%EF%BC%9Aconst%E8%BF%AD%E4%BB%A3%E5%99%A8%E5%8F%8Ainsert%E3%80%81-%E8%BF%90%E7%AE%97%E7%AC%A6%E9%87%8D%E8%BD%BD%E7%9A%84%E5%AE%9E%E7%8E%B0"><span class="toc-number">2.5.2.</span> <span class="toc-text">map：const迭代器及insert、[ ]运算符重载的实现</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#3-%E4%BB%A3%E7%A0%81%E5%B1%95%E7%A4%BA"><span class="toc-number">3.</span> <span class="toc-text">3.代码展示</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%B8%8C%E6%9C%9B%E8%AF%BB%E8%80%85%E4%BB%AC%E5%A4%9A%E5%A4%9A%E4%B8%89%E8%BF%9E%E6%94%AF%E6%8C%81"><span class="toc-number">4.</span> <span class="toc-text">希望读者们多多三连支持</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%B0%8F%E7%BC%96%E4%BC%9A%E7%BB%A7%E7%BB%AD%E6%9B%B4%E6%96%B0"><span class="toc-number">5.</span> <span class="toc-text">小编会继续更新</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BD%A0%E4%BB%AC%E7%9A%84%E9%BC%93%E5%8A%B1%E5%B0%B1%E6%98%AF%E6%88%91%E5%89%8D%E8%BF%9B%E7%9A%84%E5%8A%A8%E5%8A%9B%EF%BC%81"><span class="toc-number">6.</span> <span class="toc-text">你们的鼓励就是我前进的动力！</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2025/07/28/Linux/Linux%E7%8E%AF%E5%A2%83%E5%9F%BA%E7%A1%80%E5%BC%80%E5%8F%91%E5%B7%A5%E5%85%B7%E4%BD%BF%E7%94%A8/" title="【Linux操作系统】简学深悟启示录：Linux环境基础开发工具使用"><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250728114434.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="【Linux操作系统】简学深悟启示录：Linux环境基础开发工具使用"/></a><div class="content"><a class="title" href="/2025/07/28/Linux/Linux%E7%8E%AF%E5%A2%83%E5%9F%BA%E7%A1%80%E5%BC%80%E5%8F%91%E5%B7%A5%E5%85%B7%E4%BD%BF%E7%94%A8/" title="【Linux操作系统】简学深悟启示录：Linux环境基础开发工具使用">【Linux操作系统】简学深悟启示录：Linux环境基础开发工具使用</a><time datetime="2025-07-28T13:41:39.000Z" title="发表于 2025-07-28 21:41:39">2025-07-28</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2025/07/14/Linux/Linux%E6%9D%83%E9%99%90/" title="【Linux操作系统】简学深悟启示录：Linux权限"><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250713233449.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="【Linux操作系统】简学深悟启示录：Linux权限"/></a><div class="content"><a class="title" href="/2025/07/14/Linux/Linux%E6%9D%83%E9%99%90/" title="【Linux操作系统】简学深悟启示录：Linux权限">【Linux操作系统】简学深悟启示录：Linux权限</a><time datetime="2025-07-13T22:00:00.000Z" title="发表于 2025-07-14 06:00:00">2025-07-14</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2025/07/07/Linux/Linux%E5%9F%BA%E6%9C%AC%E6%8C%87%E4%BB%A4/" title="【Linux操作系统】简学深悟启示录：Linux基本指令"><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250705182234.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="【Linux操作系统】简学深悟启示录：Linux基本指令"/></a><div class="content"><a class="title" href="/2025/07/07/Linux/Linux%E5%9F%BA%E6%9C%AC%E6%8C%87%E4%BB%A4/" title="【Linux操作系统】简学深悟启示录：Linux基本指令">【Linux操作系统】简学深悟启示录：Linux基本指令</a><time datetime="2025-07-07T12:31:51.000Z" title="发表于 2025-07-07 20:31:51">2025-07-07</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2025/06/23/%E5%89%8D%E7%AB%AF%E5%9F%BA%E7%A1%80/css%EF%BC%88%E4%B8%8B%EF%BC%89/" title="【前端基础】层叠宇宙的代码旅人：css（下）"><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250608235413.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="【前端基础】层叠宇宙的代码旅人：css（下）"/></a><div class="content"><a class="title" href="/2025/06/23/%E5%89%8D%E7%AB%AF%E5%9F%BA%E7%A1%80/css%EF%BC%88%E4%B8%8B%EF%BC%89/" title="【前端基础】层叠宇宙的代码旅人：css（下）">【前端基础】层叠宇宙的代码旅人：css（下）</a><time datetime="2025-06-23T07:47:50.000Z" title="发表于 2025-06-23 15:47:50">2025-06-23</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2025/06/23/%E5%89%8D%E7%AB%AF%E5%9F%BA%E7%A1%80/css%EF%BC%88%E4%B8%AD%EF%BC%89/" title="【前端基础】层叠宇宙的代码旅人：css（中）"><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/909e58aa338befce9e0b2e4e683d50c.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="【前端基础】层叠宇宙的代码旅人：css（中）"/></a><div class="content"><a class="title" href="/2025/06/23/%E5%89%8D%E7%AB%AF%E5%9F%BA%E7%A1%80/css%EF%BC%88%E4%B8%AD%EF%BC%89/" title="【前端基础】层叠宇宙的代码旅人：css（中）">【前端基础】层叠宇宙的代码旅人：css（中）</a><time datetime="2025-06-23T07:44:20.000Z" title="发表于 2025-06-23 15:44:20">2025-06-23</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2024 - 2025 By 澪贰</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo 7.3.0</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly 5.3.5</a></div><div class="footer_custom_text">🏃‍➡️不是遇到同行伙伴再出发，而是出发后的路上遇到志同道合的人。<p></a>&nbsp;<a target="_blank" href="https://www.jsdelivr.com/"><img src= "" data-lazy-src="https://img.shields.io/badge/CDN-jsDelivr-orange?style=flat&logo=jsDelivr" title="本站使用JsDelivr为静态资源提供CDN加速"></a> &nbsp;<a target="_blank" href="https://vercel.com/ "><img src= "" data-lazy-src="https://img.shields.io/badge/Hosted-Vervel-brightgreen?style=flat&logo=Vercel" title="本站采用双线部署，默认线路托管于Vercel"></a>&nbsp;<a target="_blank" href="https://vercel.com/ "><img src= "" data-lazy-src="https://img.shields.io/badge/Hosted-Coding-0cedbe?style=flat&logo=Codio" title="本站采用双线部署，联通线路托管于Coding"></a>&nbsp;<a target="_blank" href="https://github.com/"><img src= "" data-lazy-src="https://img.shields.io/badge/Source-Github-d021d6?style=flat&logo=GitHub" title="本站项目由Gtihub托管"></a>&nbsp;<a target="_blank" href="http://creativecommons.org/licenses/by-nc-sa/4.0/"><img src= "" data-lazy-src="https://img.shields.io/badge/Copyright-BY--NC--SA%204.0-d42328?style=flat&logo=Claris" title="本站采用知识共享署名-非商业性使用-相同方式共享4.0国际许可协议进行许可"></a></p></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="日间和夜间模式切换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="前往评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"><span id="percent">0</span><span>%</span></i></button><button id="go-down" type="button" title="直达底部" onclick="btf.scrollToDest(document.body.scrollHeight, 500)"><i class="fas fa-arrow-down"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/medium-zoom/dist/medium-zoom.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><div class="js-pjax"><script>(() => {
  const isShuoshuo = GLOBAL_CONFIG_SITE.pageType === 'shuoshuo'
  const option = null

  const getCount = () => {
    const countELement = document.getElementById('twikoo-count')
    if(!countELement) return
    twikoo.getCommentsCount({
      envId: 'https://twikoo.zzh-blog.club/',
      region: '',
      urls: [window.location.pathname],
      includeReply: false
    }).then(res => {
      countELement.textContent = res[0].count
    }).catch(err => {
      console.error(err)
    })
  }

  const init = (el = document, path = location.pathname) => {
    twikoo.init({
      el: el.querySelector('#twikoo-wrap'),
      envId: 'https://twikoo.zzh-blog.club/',
      region: '',
        placeholder: "|´・ω・)ノ嘿~都看到这儿了\n确定不评论一下再走嘛？\n(点完发送按钮等几秒哦~)",
        nicknamePlaceholder: "昵称/笔名",
        emailPlaceholder: "邮箱（不会公开）",
        urlPlaceholder: "个人站点",
      onCommentLoaded: () => {
        btf.loadLightbox(document.querySelectorAll('#twikoo .tk-content img:not(.tk-owo-emotion)'))
      },
      ...option,
      path: isShuoshuo ? path : (option && option.path) || path
    })

    

    isShuoshuo && (window.shuoshuoComment.destroyTwikoo = () => {
      if (el.children.length) {
        el.innerHTML = ''
        el.classList.add('no-comment')
      }
    })
  }

  const loadTwikoo = (el, path) => {
    if (typeof twikoo === 'object') setTimeout(() => init(el, path), 0)
    else btf.getScript('https://cdn.jsdelivr.net/npm/twikoo/dist/twikoo.all.min.js').then(() => init(el, path))
  }

  if (isShuoshuo) {
    'Twikoo' === 'Twikoo'
      ? window.shuoshuoComment = { loadComment: loadTwikoo }
      : window.loadOtherComment = loadTwikoo
    return
  }

  if ('Twikoo' === 'Twikoo' || !true) {
    if (true) btf.loadComment(document.getElementById('twikoo-wrap'), loadTwikoo)
    else loadTwikoo()
  } else {
    window.loadOtherComment = loadTwikoo
  }
})()</script></div><script defer src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script><script defer data-pjax src="/js/cat.js"></script><canvas id="universe"></canvas><script defer src="/js/universe.js"></script><script async src="/js/title.js"></script><script async src="//npm.elemecdn.com/pace-js@1.2.4/pace.min.js"></script><script defer data-pjax src="/js/readPercent.js"></script><div class="aplayer no-destroy" data-id="8459282733" data-server="netease" data-type="playlist" data-fixed="true" data-autoplay="true" data-listmaxheight=400px data-order="random"> </div><script src="https://cdn.staticfile.org/jquery/3.6.3/jquery.min.js"></script><script async data-pjax src="/js/txmap.js"></script><script src="source/js/统计图颜色适配.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = true;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-heart.min.js" async="async" mobile="true"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/metingjs/dist/Meting.min.js"></script><script>(() => {
  const destroyAplayer = () => {
    if (window.aplayers) {
      for (let i = 0; i < window.aplayers.length; i++) {
        if (!window.aplayers[i].options.fixed) {
          window.aplayers[i].destroy()
        }
      }
    }
  }

  const runMetingJS = () => {
    typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()
  }

  btf.addGlobalFn('pjaxSend', destroyAplayer, 'destroyAplayer')
  btf.addGlobalFn('pjaxComplete', loadMeting, 'runMetingJS')
})()</script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>(() => {
  const pjaxSelectors = ["head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show",".js-pjax"]

  window.pjax = new Pjax({
    elements: 'a:not([target="_blank"])',
    selectors: pjaxSelectors,
    cacheBust: false,
    analytics: false,
    scrollRestoration: false
  })

  const triggerPjaxFn = (val) => {
    if (!val) return
    Object.values(val).forEach(fn => fn())
  }

  document.addEventListener('pjax:send', () => {
    // removeEventListener
    btf.removeGlobalFnEvent('pjaxSendOnce')
    btf.removeGlobalFnEvent('themeChange')

    // reset readmode
    const $bodyClassList = document.body.classList
    if ($bodyClassList.contains('read-mode')) $bodyClassList.remove('read-mode')

    triggerPjaxFn(window.globalFn.pjaxSend)
  })

  document.addEventListener('pjax:complete', () => {
    btf.removeGlobalFnEvent('pjaxCompleteOnce')
    document.querySelectorAll('script[data-pjax]').forEach(item => {
      const newScript = document.createElement('script')
      const content = item.text || item.textContent || item.innerHTML || ""
      Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
      newScript.appendChild(document.createTextNode(content))
      item.parentNode.replaceChild(newScript, item)
    })

    triggerPjaxFn(window.globalFn.pjaxComplete)
  })

  document.addEventListener('pjax:error', e => {
    if (e.request.status === 404) {
      const usePjax = true
      true 
        ? (usePjax ? pjax.loadUrl('/404.html') : window.location.href = '/404.html')
        : window.location.href = e.request.responseURL
    }
  })
})()</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="text-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="输入你想搜索的关键字" type="text"/></div></div><hr/><div id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></div><!-- hexo injector body_end start --><script data-pjax>
    function butterfly_categories_card_injector_config(){
      var parent_div_git = document.getElementById('recent-posts');
      var item_html = '<style>li.categoryBar-list-item{width:24%;}.categoryBar-list{max-height: 380px;overflow:auto;}.categoryBar-list::-webkit-scrollbar{width:0!important}@media screen and (max-width: 650px){.categoryBar-list{max-height: 320px;}}</style><div class="recent-post-item" style="height:auto;width:100%;padding:0px;"><div id="categoryBar"><ul class="categoryBar-list"><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163139.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/Linux/&quot;);" href="javascript:void(0);">Linux</a><span class="categoryBar-list-count">3</span><span class="categoryBar-list-descr">C++笔记</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163140.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/C-初阶/&quot;);" href="javascript:void(0);">C++初阶</a><span class="categoryBar-list-count">19</span><span class="categoryBar-list-descr">C语言笔记</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_202507101631401.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/C语言/&quot;);" href="javascript:void(0);">C语言</a><span class="categoryBar-list-count">22</span><span class="categoryBar-list-descr">Linux笔记</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163130.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/Microi吾码/&quot;);" href="javascript:void(0);">Microi吾码</a><span class="categoryBar-list-count">2</span><span class="categoryBar-list-descr">C++笔记</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163135.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/C-进阶/&quot;);" href="javascript:void(0);">C++进阶</a><span class="categoryBar-list-count">19</span><span class="categoryBar-list-descr">低代码</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163137.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/优选算法/&quot;);" href="javascript:void(0);">优选算法</a><span class="categoryBar-list-count">11</span><span class="categoryBar-list-descr">数据结构笔记</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163136.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/前端基础/&quot;);" href="javascript:void(0);">前端基础</a><span class="categoryBar-list-count">5</span><span class="categoryBar-list-descr">入门常用算法</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163132.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/话题/&quot;);" href="javascript:void(0);">话题</a><span class="categoryBar-list-count">5</span><span class="categoryBar-list-descr">前端基础笔记</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163134.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/初阶数据结构/&quot;);" href="javascript:void(0);">初阶数据结构</a><span class="categoryBar-list-count">10</span><span class="categoryBar-list-descr">杂谈</span></li></ul></div></div>';
      console.log('已挂载butterfly_categories_card')
      parent_div_git.insertAdjacentHTML("afterbegin",item_html)
      }
    if( document.getElementById('recent-posts') && (location.pathname ==='/'|| '/' ==='all')){
    butterfly_categories_card_injector_config()
    }
  </script><script data-pjax>
  function butterfly_footer_beautify_injector_config(){
    var parent_div_git = document.getElementById('footer-wrap');
    var item_html = '<div id="workboard"></div><p id="ghbdages"><a class="github-badge" target="_blank" href="https://hexo.io/" style="margin-inline:5px" data-title="博客框架为Hexo" title=""><img src= "" data-lazy-src="https://img.shields.io/badge/Frame-Hexo-blue?style=flat&amp;logo=hexo" alt=""/></a><a class="github-badge" target="_blank" href="https://butterfly.js.org/" style="margin-inline:5px" data-title="主题使用Butterfly" title=""><img src= "" data-lazy-src="https://img.shields.io/badge/Theme-Butterfly-6513df?style=flat&amp;logo=bitdefender" alt=""/></a></p>';
    console.log('已挂载butterfly_footer_beautify')
    parent_div_git.insertAdjacentHTML("beforeend",item_html)
    }
  var elist = 'null'.split(',');
  var cpage = location.pathname;
  var epage = 'all';
  var flag = 0;

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_footer_beautify_injector_config();
  }
  else if (epage === cpage){
    butterfly_footer_beautify_injector_config();
  }
  </script><script async src="https://unpkg.zhimg.com/hexo-butterfly-footer-beautify@1.0.0/lib/runtime.min.js"></script><script data-pjax>
  function butterfly_swiper_injector_config(){
    var parent_div_git = document.getElementById('recent-posts');
    var item_html = '<div class="recent-post-item" style="height: auto;width: 100%"><div class="blog-slider swiper-container-fade swiper-container-horizontal" id="swiper_container"><div class="blog-slider__wrp swiper-wrapper" style="transition-duration: 0ms;"><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;2025/02/28/话题/DeepSeek、Grok 和 ChatGPT 对比分析/&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/77c5921463a44f418828ae47de6671e5.webp" alt="" onerror="this.src=https://unpkg.zhimg.com/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2025-02-28</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;2025/02/28/话题/DeepSeek、Grok 和 ChatGPT 对比分析/&quot;);" href="javascript:void(0);" alt="">DeepSeek、Grok 和 ChatGPT 对比分析：从技术与应用场景的角度深入探讨</a><div class="blog-slider__text">在人工智能领域，随着技术的快速发展，不同的工具和框架不断涌现，为开发者提供了更多选择。DeepSeek、Grok 和 ChatGPT 作为三款备受关注的工具，每一款都有其独特的优势和适用场景。本文将从技术特点、应用场景以及实际案例分析的角度，对这三款工具进行对比，帮助读者更好地理解它们的区别和适用场景</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;2025/02/28/话题/DeepSeek、Grok 和 ChatGPT 对比分析/&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;2025/02/20/话题/C++方向后端开发学习指南/&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/44fa280c73e53024f749363207753e1.png" alt="" onerror="this.src=https://unpkg.zhimg.com/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2025-02-20</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;2025/02/20/话题/C++方向后端开发学习指南/&quot;);" href="javascript:void(0);" alt="">当前就业形势下C++方向后端开发学习指南</a><div class="blog-slider__text">在信息技术飞速发展的今天，后端开发成为了软件开发领域中极其重要的组成部分。对于很多程序员来说，C++仍然是一个强大且广泛应用的编程语言，尤其在后端开发中有着不可忽视的地位。本文将深入探讨C++方向后端开发的学习路线，分析当前就业形势下的职业方向选择，并结合图示和代码示例，帮助读者系统化地学习C++后端开发</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;2025/02/20/话题/C++方向后端开发学习指南/&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;2025/02/20/话题/AIGC训练效率/&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/419f4f95b11526f92f62fe38778d0a9.png" alt="" onerror="this.src=https://unpkg.zhimg.com/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2025-02-20</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;2025/02/20/话题/AIGC训练效率/&quot;);" href="javascript:void(0);" alt="">AIGC训练效率与模型优化的深入探讨</a><div class="blog-slider__text">人工智能领域的发展，人工智能生成内容（ [AIGC](https://aigc.izzi.cn/)）越来越受关注。AIGC能够通过学习大量数据生成高质量内容，但训练效率和模型优化仍然是关键的研究方向。本博客将深入探AIGC的训练效率，与模型优化的相关策略和技术，提供相应代码示例和图示，以帮助读者更好地理解该领域</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;2025/02/20/话题/AIGC训练效率/&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;2025/02/28/话题/如何高效利用DeepSeek/&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/e640e59c2f92482993b52c845adf7844.webp" alt="" onerror="this.src=https://unpkg.zhimg.com/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2025-02-28</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;2025/02/28/话题/如何高效利用DeepSeek/&quot;);" href="javascript:void(0);" alt="">如何高效利用DeepSeek：深入探索AI搜索引擎的潜力</a><div class="blog-slider__text">随着人工智能技术的飞速发展，传统的搜索引擎正逐步向更智能化、个性化的方向演进。作为一款基于深度学习的AI搜索引擎，DeepSeek（深度求索）不仅在理解用户意图方面展现出色，还通过集成丰富的知识图谱和提供多样化的信息类型，成为现代用户的信息获取利器。本文将详细分析如何高效利用DeepSeek，探讨其核心技术、实际应用场景以及性能优化方法</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;2025/02/28/话题/如何高效利用DeepSeek/&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;2025/01/31/话题/本地部署Deepseek/&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/2373381f0feae7cd4964af546e9e462.png" alt="" onerror="this.src=https://unpkg.zhimg.com/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2025-01-31</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;2025/01/31/话题/本地部署Deepseek/&quot;);" href="javascript:void(0);" alt="">如何快速高效本地部署DeepseekR1大模型？保姆级教程 无惧隐私威胁</a><div class="blog-slider__text">DeepSeek 隐私政策中提到了关于用户输入信息收集的条款，无论你输入什么文本，以及上传什么文件都会被第三方机构所收集，所以如果是在进行相关的项目研究或者实验进展分析的时候，就很有必要对数据进行隐私保护，且本地部署是支持离线的</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;2025/01/31/话题/本地部署Deepseek/&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div></div><div class="blog-slider__pagination swiper-pagination-clickable swiper-pagination-bullets"></div></div></div>';
    console.log('已挂载butterfly_swiper')
    parent_div_git.insertAdjacentHTML("afterbegin",item_html)
    }
  var elist = 'undefined'.split(',');
  var cpage = location.pathname;
  var epage = '/';
  var flag = 0;

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_swiper_injector_config();
  }
  else if (epage === cpage){
    butterfly_swiper_injector_config();
  }
  </script><script defer src="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiper.min.js"></script><script defer data-pjax src="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiper_init.js"></script><script data-pjax src="https://npm.elemecdn.com/hexo-filter-gitcalendar/lib/gitcalendar.js"></script><script data-pjax>
  function gitcalendar_injector_config(){
      var parent_div_git = document.getElementById('gitZone');
      var item_html = '<div class="recent-post-item" id="gitcalendarBar" style="width:100%;height:auto;padding:10px;"><style>#git_container{min-height: 280px}@media screen and (max-width:650px) {#git_container{min-height: 0px}}</style><div id="git_loading" style="width:10%;height:100%;margin:0 auto;display: block;"><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 50 50" style="enable-background:new 0 0 50 50" xml:space="preserve"><path fill="#d0d0d0" d="M25.251,6.461c-10.318,0-18.683,8.365-18.683,18.683h4.068c0-8.071,6.543-14.615,14.615-14.615V6.461z" transform="rotate(275.098 25 25)"><animatetransform attributeType="xml" attributeName="transform" type="rotate" from="0 25 25" to="360 25 25" dur="0.6s" repeatCount="indefinite"></animatetransform></path></svg><style>#git_container{display: none;}</style></div><div id="git_container"></div></div>';
      parent_div_git.insertAdjacentHTML("afterbegin",item_html)
      console.log('已挂载gitcalendar')
      }

    if( document.getElementById('gitZone') && (location.pathname ==='/about/'|| '/about/' ==='all')){
        gitcalendar_injector_config()
        GitCalendarInit("https://gitcalendar.zzh-blog.club/api?ZeroCoder-Zhang",['#d9e0df', '#c6e0dc', '#a8dcd4', '#9adcd2', '#89ded1', '#77e0d0', '#5fdecb', '#47dcc6', '#39dcc3', '#1fdabe', '#00dab9'],'ZeroCoder-Zhang')
    }
  </script><div class="js-pjax"><script async="async">var arr = document.getElementsByClassName('recent-post-item');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__zoomIn');
    arr[i].setAttribute('data-wow-duration', '2s');
    arr[i].setAttribute('data-wow-delay', '1s');
    arr[i].setAttribute('data-wow-offset', '100');
    arr[i].setAttribute('data-wow-iteration', '1');
  }</script><script async="async">var arr = document.getElementsByClassName('card-widget');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__zoomIn');
    arr[i].setAttribute('data-wow-duration', '');
    arr[i].setAttribute('data-wow-delay', '');
    arr[i].setAttribute('data-wow-offset', '');
    arr[i].setAttribute('data-wow-iteration', '');
  }</script></div><script defer src="https://npm.elemecdn.com/hexo-butterfly-wowjs/lib/wow.min.js"></script><script defer src="https://npm.elemecdn.com/hexo-butterfly-wowjs/lib/wow_init.js"></script><!-- hexo injector body_end end --><script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"jsonPath":"/live2dw/assets/koharu.model.json"},"display":{"position":"right","hOffset":40,"vOffset":0,"width":150,"height":300},"mobile":{"show":false},"log":false});</script></body></html>